So I’ve got some giant bugs that I’m trying to have chase the player around the scene. Quaternion.Slerp() has worked to rotate the bugs to look at the player while they’re chasing him, for the most part. However, every so often, one of the bugs rotates almost, though not exactly, 90 degrees and starts coming at my player from the side. It seems to sort of get stuck in that rotation, and if I move around until I’m almost directly behind the bug, it whips back around to face me again, before getting stuck in that rotation. If I leave the bug’s line of sight (so it stops following me) and come back, it seems to be fixed, until it randomly happens again. Sometimes it happens as soon as I enter the bug’s line of sight and other times I dance around it for five minutes without it happening. I can’t figure out what triggers this random rotation or how to fix it. I’ve been beating my head against this for a week now, with no results. Here’s the code for the bug’s attack mode. This all happens in FixedUpdate(), and “attacking” and “rotatingToAttack” are set to true once the player enter’s the bug’s line of sight. beginWaiting() starts a coroutine, which is stopped every time the player enters the bug’s line of sight.
if(attacking) {
direction = (player.transform.position - transform.position).normalized;
lookRotation = Quaternion.LookRotation(direction);
angle = Quaternion.Angle(transform.rotation, lookRotation);
if(rotatingToAttack) {
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, rotationSpeed * Time.fixedDeltaTime);
if(angle < 1f) {
rotatingToAttack = false;
}
} else {
transform.LookAt(player.transform);
}
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, speed * Time.fixedDeltaTime);
if(Vector3.Distance(player.transform.position, transform.position) <= 10f
&& transform.position.y < 0.4f) {
jump();
}
if(Vector3.Distance(player.transform.position, transform.position) > los) {
rotatingToAttack = false;
attacking = false;
beginWaiting();
}
} else {
if(Vector3.Distance(player.transform.position, transform.position) <= los) {
attack();
}
}
transform.rotation = new Quaternion(0f, transform.rotation.y, 0f, transform.rotation.w); // Lock rotation to the y and w directions
If you have any other questions about this problem, I’d be happy to clarify. I think the problem might be in the Quaternion.Slerp() function, but I don’t know how to fix it. Oh, and one last thing: I’ve noticed that occasionally my console log will blow up with tons of message that “Look rotation viewing vector is zero.” I don’t know if or how this relates, and it doesn’t seem to happen when the rotation gets skewed, but it could be helpful to consider. Thank you in advance for your help.