문제

I am creating a game and want the enemy to face the player as it follows the player. I have tried to use AffineTransform in this way:

at = new AffineTransform();
angle = Math.atan2(player.getY() - y,player.getX() - x) + (Math.PI / 2);
at.setToTranslation(x, y);
at.rotate(angle, width / 2, height / 2);

and then using g2D.drawImage(image,at,this); to draw the enemy on screen. The problem is that the enemy just faces a random location on the screen, it does rotate to face that point but it doesn't face the player as I want it to. I used the exact same code in the player class to make the player face the mouse cursor and then it worked just fine, so why doesn't it work for facing the player?

도움이 되었습니까?

해결책

One of the problems with your approach is that you do not take into consideration what angle the enemy is already facing (his image), he can be at the same (x,y) yet have any of the angles [0,360]. So your rotation seems random because while you rotate him with consideration to the player you do not rotate him with consideration to his own facing. You have to figure out what angle his image is facing, find out what angle the player is facing, then rotate him with regards to this.

I recommend adding a field to every enemy/player Enum facing (if few and limited angles) or int facing that holds the angle their image is facing.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top