# Maintaining facing direction at the end of a movement

I want to make my 2D top-down walking animation stop and revert to the idle animation while continuing to face in the same direction as the previous movement.

For example, when I go up then stop, my character should continue to look up. If I go down, it should continue to look down.

I use lastmoveX and lastmoveY floats for idle and for walking I use moveX and moveY floats. moveX and moveY change when I move with the joystick, but lastmoveX and lastmoveY do not change, and I don't know how to fix this.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
private Rigidbody2D myRB;
private Animator myAnim;
public Joystick joystick;
public MoveByTouch controller;

[SerializeField]
private float speed;

// Use this for initialization
void Start ()
{
myRB = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();

}

// Update is called once per frame
void Update ()
{
myRB.velocity = new Vector2(joystick.Horizontal, joystick.Vertical) * speed * Time.deltaTime;

myAnim.SetFloat("moveX", myRB.velocity.x);
myAnim.SetFloat("moveY", myRB.velocity.y);

if(joystick.Horizontal == 1 || joystick.Horizontal == -1 || joystick.Vertical == 1 || joystick.Vertical == -1)
{
myAnim.SetFloat("lastMoveX", joystick.Horizontal);
myAnim.SetFloat("lastMoveY", joystick.Vertical);
}

}
}


My guess is that your joystick is never hitting exactly +-1 on either axis. maybe it hits 0.999, which is far enough away that joystick.Horizontal == 1 would report "false", fail the if, and never execute the code that updates the lastMove variables. (This is why we have to be careful about comparing floating point numbers for exact equality)

Have you tried making the if condition more permissive, to trigger on any non-zero input? Something like this should do decently:

void Update ()
{
myRB.velocity = new Vector2(joystick.Horizontal, joystick.Vertical) * speed;

myAnim.SetFloat("moveX", myRB.velocity.x);
myAnim.SetFloat("moveY", myRB.velocity.y);

if(!Mathf.Approximately(joystick.Horizontal, 0) || !Mathf.Approximately(joystick.Vertical, 0))
{
myAnim.SetFloat("lastMoveX", joystick.Horizontal);
myAnim.SetFloat("lastMoveY", joystick.Vertical);
}
}


(I deleted the * Time.deltaTime from your velocity calculation, as it is not appropriate to use there)

• Yeah it worked thanks for help – Wallroad Mar 9 at 22:34
• You can click the checkmark icon next to the answer to mark it as "Accepted" if it solves your problem. – DMGregory Mar 9 at 22:40