0

So I have the code below that enables a block to follow the player. The block moves at a constant speed and rotates itself to the direction of the player to follow. However, the block only follows the player when it's above the player. When the block is below the player, it goes straight down instead of the direction of the player. I am wondering if there are any adjustments I could make in my algorithm to accomplish this task.

xMove = speed * Math.sin(angle);
yMove = speed * Math.cos(angle);

if(radarRange().intersects(Player.getPlayerData().getBounds())) {

    double sx = x + width/2;
    double sy = y + height/2;

    double ex = Player.getPlayerData().getX() + Player.getPlayerData().getBounds().width/2;
    double ey = Player.getPlayerData().getY() + Player.getPlayerData().getBounds().height/2;

    double requiredAngle = Math.atan2(ex - sx, ey - sy);

    if(angle < requiredAngle) {

        turnTimer += System.currentTimeMillis() - lastTurnTimer;
        lastTurnTimer = System.currentTimeMillis();

        if (turnTimer < turnCooldown)
            return;

        angle += Math.PI/25;

        turnTimer = 0;

    } else if(angle > requiredAngle) {

        turnTimer += System.currentTimeMillis() - lastTurnTimer;
        lastTurnTimer = System.currentTimeMillis();

        if (turnTimer < turnCooldown)
            return;

        angle -= Math.PI/25;

        turnTimer = 0;

    }

}
Alan Sun
  • 1
  • 1

1 Answers1

0

First, I am assuming that you are dealing with angles in the range 0 to 2 Pi (ie the usual radians range).

If that is the case, then you are probably getting caught by the fact that Math.atan2 doesn’t use that, but instead returns a value in the range -Pi .. Pi.

racraman
  • 4,988
  • 1
  • 16
  • 16
  • I think that could be the reason. Does that mean I just have to add Math.PI to requiredAngle? – Alan Sun Feb 01 '20 at 16:12
  • Not quite - I think the 0..Pi values are valid, so you have to map the negative values to after those. You can work from the answer at https://stackoverflow.com/questions/1311049/how-to-map-atan2-to-degrees-0-360 which is `(x > 0 ? x : (2*PI + x)) * 360 / (2*PI)` – racraman Feb 03 '20 at 01:10