Character not animating properly

Viewed 41

So, I've been trying to get my character to look where my mouse cursor is, but it's not working and it's very inconsistent. I'm sorry I don't know how to show video.

Here's the code.

    if (CanDirectionChange)
    {
        Direction.x = Input.GetAxisRaw("Horizontal");
        Direction.y = Input.GetAxisRaw("Vertical");

        Anim.SetFloat("X", MousePos.x);
        Anim.SetFloat("Y", MousePos.y);
        Anim.SetFloat("Speed", Direction.sqrMagnitude);

        if (MousePos.x>=1 || MousePos.x>=-1 || MousePos.y<=1 || MousePos.y<=-1)
        {
            Anim.SetFloat("LastX", MousePos.x);
            Anim.SetFloat("LastY", MousePos.y);
        }
    }

The Character looks where the LastX and LastY positions are.

Also the Animator looks like this.

Animtor

1 Answers

I think the problem is in the incredibly confusing if statement.

if ( MousePos.x>=1 || MousePos.x>=-1 || MousePos.y<=1 || MousePos.y<=-1 )

is your current condition, but the Greater than sign is facing the same way both times. Because of the numerous conditions, your code essentially runs like this:

if ( MousePos.x>=1 || MousePos.y<=-1 )

because whenever MousPos.x is is bigger than 1, it is also bigger than -1, and when MousePos.y is smaller than -1 it is also smaller than 1.

Im assuming the function of the if statement is to prevent looking at it when the mouse cursor is close, so the proper way to do that is

float Dist = Mathf.Sqrt(Mathf.Pow((MousePos.x),2) + Mathf.Pow((MousePos.y), 2));
if (Dist >= LookAtDistance)

The reason behind the square roots and exponents is because it is a circle, where as previously it would have a square shaped ignorance range.

If you want your player to ignore the mouse based on a square shape, the code would look like:

if ( MousePos.x>=1 || MousePos.x<=-1 || MousePos.y>=1 || MousePos.y<=-1 )
Related