So I've been trying to make an object move based on two speeds that it creates using atan(). But every test results in the same movement of going straight up.
So I decided to take that out and replace it with inputted angles which oddly does only work for the the four angles 90 180 270 0.
I'm not sure why it only goes for only those for directions here's my code:
public void update() {
updateDir();
move();
}
public void updateDir(){
dir = Math.atan(spdY/spdX);
dir =20; //I know this is here it was used to test if it will actually change
dir = dir * Math.PI / 180.0;
System.out.println("dir: " + dir);
}
public void move() {
x += (spd*Math.cos(dir));
y -= (spd * Math.sin(dir));
}
Any reason why it only goes in 4 directions?
What @Nishant Shreshth says is true. But it is also super important to use floating points (like
float
ordouble
) instead ofint
for yourdir
,x
andy
variable. Otherwise the decimal part yourdir
value might be truncated, which is pretty much of a problem when you use radians and trigonometric functions.Also note that you probably want to use
Math.atan2(spdY, spdX)
instead of the default atan method you use. Your approach will fail as soon asspdX
gets zero: you will divide by zero.atan2
will take care of these edge cases. Wikipedia gives details on this function.