Change Animation According to Direction

Hello,

I’m working on a RTS game,

I have a character that has 5 animations attached: Idle, Run, RunLeft, RunRight, RunBack. What I need to do, is use these animations for my character depending on the direction he’s running.

By default, the character will always run in a forward direction to wherever I click, so I only need to use the Run animation.

But, when the character comes into close proximity with an enemy, his rotation will always face the enemy, but will continue to run in the direction of wherever I clicked on the map.

This is where I need the change the animation playing, as he may be facing North at the enemy, but running East, so I will need to play the RunRight animation instead of the Run (forward) animation.

I need to somehow use the current character rotation against the marker (the click location of the mouse, on the map) so select between my animations:

//If we are in proximity to an enemy, then face it, but continue to run towards click marker
if(finder.target){
	transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(finder.target.position - transform.position), turnSpeed * Time.deltaTime);
	transform.position = Vector3.MoveTowards(transform.position, nav.CurrentTargetWaypoint, runSpeed * Time.deltaTime);
}
//Otherwise, face the the click marker, and run towards
else{
	transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(nav.CurrentTargetWaypoint - transform.position), turnSpeed * Time.deltaTime);
	transform.position += transform.forward * runSpeed * Time.deltaTime;
}

transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0);

//Animation control
if(hasAnimation){
	anim.characterToAnimate.animation.CrossFade(anim.Run.name, .1f);
}

Okay,

So I’ve been messing and tweaking, and I’ve seemed to have done it, although I’m not sure if this is the best way to do it:

//Animation control
if(hasAnimation){

	if(finder.target){
		
		var angleBetween = Quaternion.Angle(transform.rotation, Quaternion.LookRotation(nav.CurrentTargetWaypoint - transform.position));

		if(angleBetween > 0 && angleBetween < 90)
			anim.characterToAnimate.animation.CrossFade(anim.RunRight.name, .1f);

		else if(angleBetween > 270 && angleBetween < 360)
			anim.characterToAnimate.animation.CrossFade(anim.RunLeft.name, .1f);

		else if(angleBetween > 90 && angleBetween < 270)
			anim.characterToAnimate.animation.CrossFade(anim.RunBack.name, .1f);

		else
			anim.characterToAnimate.animation.CrossFade(anim.Run.name, .1f);
	}
	else
		anim.characterToAnimate.animation.CrossFade(anim.Run.name, .1f);

}

I’m basically just changing the animation based on every 90 degree angle the character is at compared to the nav marker.

Hope this helps someone.