- Home /
Enemy follow/chase behaviour glitching when using rotateTowards
I'm using the following method to detect when the player is within range of an enemy. If they are then the enemy both moves and rotates towards them:
function FixedUpdate()
{
if (player)
{
distance = Vector3.Distance( player.transform.position, transform.position);
if ( distance < 1.8 && distance > 0.05 )
{
var delta = player.transform.position - transform.position;
delta.Normalize();
var speed = moveSpeed;
rigidbody.velocity = delta * moveSpeed;
lookAt();
}
}
}
function lookAt (){
var targetDir = player.transform.position - transform.position;
var step = rotSpeed * Time.deltaTime;
var newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0);
Debug.DrawRay(transform.position, newDir, Color.red);
transform.rotation = Quaternion.LookRotation(newDir);
}
The behaviour works, but when a group of enemies start flocking together, they fight with one another and start rotating around their x, y and z axis. The effect is only momentary, and seems strongest when the player quickly passes the group of enemies at close range, but it's still quite jarring.
The effect also happens with rotation locked to just the Y axis.
I have searched for solutions, and don't want to use LookAT, as don't want the enemies rotation to "snap" to the player when within range, but transition over a short amount of time. None of the similar posts I viewed contained a viable solution. I appreciate my code is anything but elegant, but I'm just trying to get the thing working for the moment.
The documentation states that rotateTowards is similar in operation to moveTowards. Is rotateTowards fighting the physics by forcing the angle, and are their any suitable alternatives?
Your answer
![](https://koobas.hobune.stream/wayback/20220613115933im_/https://answers.unity.com/themes/thub/images/avi.jpg)