Smoothly rotate a rigidbody enemy 180 degrees when reaching a waypoint and path back to original waypoint

Hey guys,

I’ve got a 2d platformer here and what I’m trying to do is have my enemy travel to one waypoint and then rotate 180 degrees (smoothly… I don’t want to use transform.LookAt because that simply creates a choppy visual effect). I want to rotate him on the y axis 180 degrees to face the original waypoint and then travel back to that waypoint (and then loop the waypoint system). Right now my code has the enemy ping ponging from waypoint to waypoint. No rotation when reaching the next waypoint. Any ideas? Here is the script:

var pathpoint : Transform;

var currentPathPoint : int;

var speed : float = 5;

var loop : boolean = true;

var rotateSpeed : float = 300;

function Awake (){

pathpoint[0] = transform; }

function Update(){

if(currentPathPoint < pathpoint.length){

var target : Vector3 = pathpoint[currentPathPoint].position;

var moveDirection : Vector3 = target - transform.position;

moveDirection.y = 0;

var velocity = rigidbody.velocity;

if(moveDirection.magnitude < 1){

currentPathPoint++;

enemyRotate = Quaternion.FromToRotation(Vector3.forward, moveDirection);

pathpoint[currentPathPoint].rotation = Quaternion.RotateTowards(pathpoint[currentPathPoint].rotation, enemyRotate, rotateSpeed * Time.deltaTime);

}

else{

velocity = moveDirection.normalized * speed; }
}

else{

if(loop){
currentPathPoint = 0; }
}

rigidbody.velocity = velocity;
}

Your current code says that if you get within 1 of the target, you should go to the next waypoint and rotate for ONE FRAME (towards the old waypoint, even.) Next frame, you’re far from the new waypoint, so you stop turning and only move. If you want “if not facing target, spin; else move”, then say that:

float moveAngle = ...
// Vector3.Angle has an example of exactly how to get angle to a target

if(moveAngle>2) { // just picking 2 degrees as "close enough", for no reason
  // your rotation code here
}
else {
  // your move code here
}

I’m not sure why you use pathpoint[currentPathPoint].rotation instead of just transform.rotation (most people just care about waypoints’ position,) but I’m sure you have a reason.