'Follow' problem.

What a great first post, eh?

Well, I started working on a simple top-down shooter yesterday (Using the Slick library). I’ve made the enemies follow the player, but it’s somewhat buggy.

	@Override
	public void update(GameContainer gc, int delta) {
		float dx = ((Engine.getPlayer().getLocation().x + 10) - this.location.x);
		float dy = ((Engine.getPlayer().getLocation().y + 10) - this.location.y);
		this.rotation = (float) Math.toDegrees(Math.atan2(dy, dx) + 89.65f);
		
		final float SPEED = 1.0f;
				
		this.location.x += Math.cos(this.rotation) * SPEED;
		this.location.y += Math.sin(this.rotation) * SPEED;
	}

	@Override
	public void render(GameContainer gc, Graphics g) {
		sprite.setRotation(Math.round(this.rotation));
		sprite.draw(this.location.x - (sprite.getWidth() / 2), this.location.y - (sprite.getHeight() / 2));
	}

It works fine when the player isn’t moving, but when the player starts moving, the enemy starts doing all of these little circles (not rotation, but location) until the Player stops moving.

Anyone know what the issue might be?

Changing the 3rd line of update to:

this.rotation = (float) Math.toDegrees(Math.atan2(dy, dx)) + 89.65f;

should fix the problem.

I would recomend adding a member variable like:

final static float ROTATION_OFFSET = Math.toRadians(89.65f);

and change the 3rd line of the update function to:

this.rotation = (float) (Math.atan2(dy, dx) + ROTATION_OFFSET);

Always keeping the rotation variable in radians will help a lot with avoiding errors like this. If you ever want the rotation in degrees, to show the player or something, just convert it on the fly.

What zoto said, and also make sure that the angle you’re applying cos and sin to is in radians.
Simon

The problem isn’t the rotation (Although I did change my method to fit yours a bit more). It faces the player just fine.

The problem is when the player is moving, the enemy will stop moving towards the enemy, and instead do these weird little circles, causing him to be nearly stationary.

I noticed when you quoted me, you had commented out the rotation offset.

The reason I’ve got that is because my sprite wouldn’t face the right direction (he’d face 90 degrees counterclockwise of the direction he’s supposed to face.

Edit: I fixed it, I figured out what my problem was. Thanks to the two of your for your help. Much appreciated.