- Home /
Enemy rotating to look at next way point unity 3d
So I have a problem with this code, I want the enemy to rotate to look at the next waypoint. I tried this:
transform.LookAt(waypoints[waypoint].position);
But this makes it just kind of jump, I want the enemy to visably rotate. This is my code now:
void NextWaypoint()
{
waypoint++;
if (waypoint >= waypoints.Length) //if the enemy has reached the end of the waypoints
{
waypoint = 0; //starts again at 0
}
Vector3 directionTowaypoint= transform.position - waypoints[waypoint].gameObject.transform.position;
Quaternion enemyRotationtowaypoint = Quaternion.LookRotation(directionTowaypoint);
transform.rotation = Quaternion.Slerp(transform.rotation, enemyRotationtowaypoint, Time.deltaTime * 10);
}
Would appreciate some help!
Answer by MUG806 · Feb 20, 2021 at 10:34 PM
you have the right idea, you just need to put that last line inside Update(), and declare your "enemyRotationtowaypoint" at the top of the class. so like:
public class YourScript : MonoBehaviour{
Quaternion enemyRotationtowaypoint;
void Update(){
transform.rotation = Quaternion.Slerp(transform.rotation, enemyRotationtowaypoint, Time.deltaTime * 10);
}
void NextWaypoint()
{
waypoint++;
if (waypoint >= waypoints.Length) //if the enemy has reached the end of the waypoints
{
waypoint = 0; //starts again at 0
}
Vector3 directionTowaypoint= transform.position - waypoints[waypoint].gameObject.transform.position;
enemyRotationtowaypoint = Quaternion.LookRotation(directionTowaypoint);
}
}
This way slerp will rotate the object slightly towards the target rotation each frame.
sorry i didnt realise you replied. I tried this code and the enemy gets stuck on one waypoint
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
How do i get this objects y rotation the same as my cameras y rotation? 1 Answer
How to write turret aiming for enemy AI 2d side tank? 1 Answer
Distribute terrain in zones 3 Answers
How can i make a sprite move in the direction it is rotated? 1 Answer