I am currently trying to move an object (circle ball) around the canvas in a random direction.

I have already written the code for the wall collisions so the ball bounces back into canvas when the ball hits any of the canvas sides.

The canvas size is 600 x 500

in order to move the object around the canvas I have used;

   xPosition += ySpeed;
   yPosition += ySpeed;

From the code above, the ball moves from one end to the other end of the canvas in the same angle and direction, then bounces back at a different angle.

How can I go about doing this, if I wanted my object to move in the same speed but in a random direction around the canvas.

Any help is appreciated, thanks!


2 Answers 2


You want to generate a random direction vector which is normalized. Since the vector is normalized, you can then multiply that vector by your desired (scalar) speed to move in that direction with the desired speed.

One way to generate a random unit vector that avoids accidentally generating a null vector or directional bias is to randomly generate a value between 0 and 2π and using sine and cosine to give you x and y values:

angle = random(0, 2π)
direction = vector(cos(angle), sin(angle))

You can then update the ball's position by doing:

xPosition += (speed * direction.x)
yPosition += (speed * direction.y)

In your title also mention "at random times," which sounds to me like you also want the ball to change direction randomly every so often. If this is true, one way to accomplish this is to have a timer that counts down, and when it reaches zero you re-generate direction above. Once you re-generate direction, reset the timer to a random value in the desired range (say, 2 to 4 to make the ball change direction every 2 to 4 seconds, or whatever).


Decomposition into Length and Direction:

If you write a non-zero vector r as

r = ||r|| (r / ||r||) = ||r|| e_r

you have decomposed it into length ||r|| = sqrt(sum_i x_i^2) and direction vector e_r, which is a unit vector with start point at the origin and whose end point for 2D lies on the unit circle, for 3D it lies on the unit sphere.

The 2D case of the direction vector can be characterized by by using polar coordinates with r = 1 and phi from [0, 2pi).

 erx = cos(phi)
 ery = sin(phi)

Choosing such phi randomly gives random direction vectors.

Moving with constant speed but random direction:

The change in position vector dr is roughly (for small dt)

dr = v dt

for some velocity vector v and time interval dt.

For a fixed velocity magnitude S = ||v|| and random direction e_r this turns into

drx = S erx dt
dry = S ery dt

Note: You added ySpeed to xPosition which probably should be xSpeed.


You must log in to answer this question.

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