Question

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?

Was it helpful?

Solution 2

What @Nishant Shreshth says is true. But it is also super important to use floating points (like float or double) instead of int for your dir, x and y variable. Otherwise the decimal part your dir 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 as spdX gets zero: you will divide by zero. atan2 will take care of these edge cases. Wikipedia gives details on this function.

OTHER TIPS

Did you realize that the dir field never changes in your code.

Method updateDir prints the same thing no matter how many times you call it.

What's dir = 20 for? I guess you might need to recheck or get rid of that statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top