c# XNA确定Vector2是否面对另一个Vector2
本文关键字:Vector2 面对 另一个 是否 确定 XNA | 更新日期: 2023-09-27 18:17:01
我正在制作一款2D游戏。我想弄清楚如何确定一个Vector2是否面对另一个。
到目前为止我写的是:
public void update(GameTime gameTime, Vector2 playerPosition)
{
// position is "enemy" Vector2
// rotationAngle is the angle which the "enemy" is facing
// I need to determine if the "enemy" should rotate left, right, or move forward
// The goal is to have the "enemy" move towards the player
float angle = MathHelper.ToDegrees((float)Math.Atan2(playerPosition.Y - position.Y, playerPosition.X - position.X));
float rotationDegrees = MathHelper.ToDegrees(rotationAngle);
// Now what????
update(gameTime);
}
哎呀,在尝试了一些东西之后,我明白了。
public void update(GameTime gameTime, Vector2 playerPosition)
{
float angle = MathHelper.ToDegrees((float)Math.Atan2(playerPosition.Y - position.Y, playerPosition.X - position.X));
float rotationDegrees = MathHelper.ToDegrees(rotationAngle);
var diff = ((rotationDegrees - angle) + 360) % 360;
if (diff > 90)
{
// bool for rotate method determines if rotating left or right
rotate(false);
}
else
{
rotate(true);
}
if (diff < 180 && diff > 0)
{
moveForward();
}
update(gameTime);
}
编辑:我的计算有一些问题。在某些情况下,敌人会被卡住。问题在于,有时候这个值会随着每次游戏更新而从负值变为正值。解决方法是确保diff总是正的。