TolkienPotat
TolkienPotat

Reputation: 23

how to get velocity x and y from angle and speed?

I have found several answers to this, but none of them have worked for me. The go something like this:

velocityX = (int) (velocity*Math.cos(angle));
velocityY = (int) (velocity*Math.sin(angle));
        
posX += velocityX;
posY += velocityY;

This does not work for me, the angle 0 moves it directly right, every 90 degrees more in the angle changes the angle of the object 45 degrees counter-clockwise. Could it be because the center of my screen is 0, 0 and not the usual top left is 0, 0? Or is there something else I am doing wrong?

Upvotes: 1

Views: 1449

Answers (1)

Nowhere Man
Nowhere Man

Reputation: 19545

In Java, trigonometric functions such as Math.sin and Math.cos accept the argument in radians.

If the input angle is measured in degrees, it can be converted into radians using Math.toRadians helper function:

velocityX = (int) (velocity*Math.cos(Math.toRadians(angle)));
velocityY = (int) (velocity*Math.sin(Math.toRadians(angle)));

It is also possible to define a constant and use it to convert degrees to radians:

public static final double TO_RAD = Math.PI / 180;

//...

velocityX = (int) (velocity*Math.cos(angle * TO_RAD));
velocityY = (int) (velocity*Math.sin(angle * TO_RAD));

Upvotes: 4

Related Questions