I am making a 2D Game and I use the AStar pathfinding(A* Pathfinding Project) to move my NPC’s around the screen. Problem is I cannot tell which direction the NPC is moving in to update their sprite. Anyone know how I could solve this issue?
Thanks
I am making a 2D Game and I use the AStar pathfinding(A* Pathfinding Project) to move my NPC’s around the screen. Problem is I cannot tell which direction the NPC is moving in to update their sprite. Anyone know how I could solve this issue?
Thanks
You could store their previous position and compare it to their current position each frame to determine the direction they have moved in.
private Vector3 prevPosition;
public Vector3 MovementDirection { get; private set;}
void Update()
{
MovementDirection = transform.position - prevPosition;
MovementDirection.Normalize();
prevPostition = transform.position;
}
Thank you so much! It worked, this is the following code I used in case anyone else has any issues. I get my sprite animations based on a X/Y float.
movementDirection = transform.position - prevPosition;
movementDirection.Normalize();
if (anim)
{
anim.SetFloat("X", Mathf.Clamp(Mathf.Round(movementDirection.x), -1, 1));
anim.SetFloat("Y", Mathf.Clamp(Mathf.Round(movementDirection.y), -1, 1));
}
prevPosition = transform.position;
You could just use Mathf.Sign() instead of Clamp(). Doesn’t work correctly with 0, though.