Animation Scripting

Hey all,

I am trying to figure out how to script an animation of my 2D patrolling npc turning it’s back to the camera once it begins to head in an upwards direction. The patrolling movement is random, so I am trying to figure out how to write my script in such a way that the animation is triggered only when the patrol movement begins to move up along the map. Any ideas?

This code should work but it’s untested so you may have to modify it some.
I don’t know what the up axis is in your game so I assumed it was x, change this to whatever your up axis is.
Basically you just need to keep track of the NPC position at all times and see if it starts moving up.

In this code the animation will always be behind one frame of the NPC actually moving up.
This won’t be an issue though as your eyes wont be able to see the transition with that kind of resolution. If you have low framerates you can put this in a FixedUpdate instead of update but I don’t see that being an issue.

I can see where you might run into problems if your animation is not setup properly but you can always edit your animation to fit this scenario.

Animator animator;
private float currentPosition;
private float previousPosition;

void start()
{
animator = getComponent<Animator>();
currentPosition = transform.position.x;
}

void update()
{
previousPosition = currentPosition;
currentPosition = transform.position.x;

if(currentPosition > previousPosition)//this tells us the NPC is walking up
{
StartCoroutine(patrolUpAnimation());
}

}

IEnumerator patrolUpAnimation()
{
animator.Play("your animation name attached to this gameObject");
yield return new WaitForSeconds(0)//whatever number you need or 0 for no wait
}

Note: you can do this for every position by just adding a transform.position.z check as well. Then you will know exactly where an NPC is at all times and can do whatever you like with it as well.