I'm trying to make a small pariticle-like simulation, and I'm trying to make each parrticle go a random direction from one point (mouse pos). The problem is I don't know how to get the random vector that has a certain speed.

Here is what I'm trying to get the vector:

def getVector(self):
    vector = [random.randint(-100, 100), random.randint(-100, 100)]
    return vector

when I run this each particle goes either north, west, or northwest. The odd thing is when I tried to record a .gif to show this behavior the frame-rate of the .gif was 15 fps (slow comp) and the particles actually went in all directions. So in my code where I move the particles:

self.rect.x -= self.vector[0] * ttime
self.rect.y += self.vector[1] * ttime

I took away the ttime (the tick to regulate speed) and it worked but the particles were going very fast at various speed. So my question is how can i get a random vector that will give me the correct behavior


1 Answer 1


You can generate a random vector with a given fixed speed by choosing a random point on the unit circle, then scaling by the desired speed:

angle = random.uniform(0, 2.0*math.pi)
vector = [speed * math.cos(angle), speed * math.sin(angle)]

You could also choose speed randomly as well, using random.uniform(minSpeed, maxSpeed).

As for the change in behavior when ttime is included or not, I can't tell based on what you've posted, but particles going only north, west, or northwest suggests that maybe negative velocity values are treated incorrectly somehow. Perhaps it's an integer versus float type error. Your original code was generating integer velocities, but it's generally best to use floats for position and velocity values.

  • \$\begingroup\$ Ahh, Looks better, the particles that are going, south, east and southeast are dying faster for some reason but, I can figure it out from here. Thank you!:) \$\endgroup\$
    – Serial
    Commented Feb 6, 2014 at 14:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .