- Home /
How much the transform moved in it's directions
I have a character with an animator attached to it. Animator has two parameters (horizontal and vertical) which controls strafe right/left and move forward/backward. So I'm trying to set the animator parameters values based on how much characters transform moved in x and z direction. I use this code :
private Vector3 lastPosition;
private float vertical;
private float horizontal;
public bool run;
public Animator animator;
private void Update()
{
horizontal = (transform.position.x - lastPosition.x);
vertical = (transform.position.z - lastPosition.z);
float max = Mathf.Max(Mathf.Abs(horizontal), Mathf.Abs(vertical));
if (max == 0)
{
horizontal = 0;
vertical = 0;
}
else
{
horizontal /= max;
vertical /= max;
}
if (!run)
{
horizontal /= 2;
vertical /= 2;
}
animator.SetFloat("vertical", vertical);
animator.SetFloat("horizontal", horizzontal);
lastPosition = transform.position;
}
So the code works when character facing (0, 0, 1) direction but as soon as I rotate the character, thing get messed up. By the way I can't use input axis to set the animator parameters so don't suggest that, because the camera is not always behind the character and it can be rotated around character freely. So any ideas?
Whenever I have any problems with rotations and position I usually try seeing what using localPosition does ins$$anonymous$$d.
For example, try changing
horizontal = (transform.position.x - lastPosition.x);
to
horizontal = (transform.localPosition.x - lastPosition.x);
You would also have to make sure lastPosition is also based on a local position and not a world position.
please check where you are updating lastPosition
at least, update it on the Update function...
void Start(){
lastPosition = transform.position;
}
private void Update()
{
horizontal = (transform.position.x - lastPosition.x);
vertical = (transform.position.z - lastPosition.z);
float max = $$anonymous$$athf.$$anonymous$$ax($$anonymous$$athf.Abs(horizontal), $$anonymous$$athf.Abs(vertical));
lastPosition = transform.position;
...