I'm working on a 2D game. I'm trying to figure out how to determine if one Vector2 is facing the other.
Here is what I have so far:
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);
}
Gah, after just trying some stuff I figured it out.
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);
}
Edit: there were some issues with my calculations. Under certain conditions, enemies would get stuck. The issue is that sometimes the value would change from a negative to a positive value with every game update. The solution was to make sure diff was always positive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.