# Java - Adjusting the speed of an object during movement

I am trying to get an object to move (on java canvas) in the same angle but at different speed within the X and Y axis. Below you can see how i have implemented the movement of the object.

xPosition += xSpeed;
yPosition += ySpeed;


I want the object to be moving at the same angle. But speed change randomly throughout movement across the canvas.

How can I go about dealing with this?

I've tried changing the speed, such as;

  xSpeed -= 10;
ySpeed += 10;


Any help would be greatly appreciated.

• Are you taking the change of duration between animation frames into account? To ensure you get smooth animated movement, you will need to take the time elapsed since the last tick of the game loop into account. Mar 15, 2016 at 13:10

If you want to change magnitude of a vector without altering its direction (its speed without its direction, in your case), you just have to multiply each of its contained number (x and y, in your case) by the same number.

So, once you have defined a precise xSpeed and ySpeed in your code, you just have to multiply them by the same number:

// Will move the object
xPosition += xSpeed;
yPosition += ySpeed;

// Half speed by 2
xSpeed /= 2;
ySpeed /= 2;

// Will move the object on the same direction, but two times less far away.
xPosition += xSpeed;
yPosition += ySpeed;


Now it is still up to you to know how you want to "randomize" this speed. One solution could be to store somewhere your original movement on X and Y axis, and a speed factor that you could change from time to time. The code would looks like this in the initialization part:

xMovemeent = /* Your original movement on X axis */;
yMovemeent = /* Your original movement on Y axis */;
speed = 1.0; // original speed


And then, on the looped part:

xPosition += xMovement * speed;
yPosition += yMovement * speed;


You will just have to change speed value in order to change your object speed.