C# XNA 确定 Vector2 是否面对另一个 Vector2
C# XNA determine if Vector2 is facing another Vector2
我正在开发一款 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 始终为正值。
我正在开发一款 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 始终为正值。