- Home /
How do I stop my walk animation playing, when my character is idle?
I am programming a walking script for a top-down perspective RPG.
All the walking animations play correctly when walking in each direction, but when the player is not walking, the animations for the west-facing walk ( wSprites
) carry on playing. I'm not sure what's caused this.
Here is my code: thanks for your time!
public class TopDownController : MonoBehaviour
{
public Rigidbody2D body;
public SpriteRenderer SpriteRenderer;
public List<Sprite> nSprites;
public List<Sprite> neSprites;
public List<Sprite> eSprites;
public List<Sprite> seSprites;
public List<Sprite> sSprites;
public List<Sprite> swSprites;
public List<Sprite> wSprites;
public List<Sprite> nwSprites;
public float walkSpeed;
public float frameRate;
float idleTime;
Vector2 direction;
void Start()
{
}
void Update()
{
direction = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized;
body.velocity = direction * walkSpeed;
List<Sprite> directionSprites = GetSpriteDirection();
if(directionSprites != null)
{
float playTime = Time.time - idleTime;
int totalFrames = (int)(playTime * frameRate);
int frame = totalFrames % directionSprites.Count;
SpriteRenderer.sprite = directionSprites[frame];
}
else
{
idleTime = Time.time;
}
}
List<Sprite> GetSpriteDirection()
{
List<Sprite> selectedSprites = null;
if (direction.y > 0) //north
{
if (direction.x > 0)
{
selectedSprites = neSprites;
}
else if (direction.x < 0)
{
selectedSprites = nwSprites;
}
else
{
selectedSprites = nSprites;
}
}
else if (direction.y < 0) //south
{
if (direction.x > 0)
{
selectedSprites = seSprites;
}
else if (direction.x < 0)
{
selectedSprites = swSprites;
}
else
{
selectedSprites = sSprites;
}
}
else // neutral
{
if (direction.x > 0)
{
selectedSprites = eSprites;
}
else
{
selectedSprites = wSprites;
}
}
return selectedSprites;
}
}
Comment
Answer by TheIrishKraken · May 16 at 06:06 AM
Because in your code marked neutral your saying if the x direction of your player is less then 0 play the wSprites. Your code is suggesting that if all the code above line 95 is not true then play the wSprite.