Currently I’m writing a space station game that has ships flying around the station, following a set of waypoints, and then ultimately ending up at the front of the station ready to perform the next, yet-to-be-written docking function.
As of now, I’m able to have the object follow the waypoints by slerping between them, but I wanted to have the ships facing the direction they are moving. I was able to use transform.LookAt() to make the object face the next waypoint, however this results in a hard snap in the direction of the next waypoint.
I assume I’ll have to use an additional slerping function to do this but I’m not sure how.
This is the code that I’m using for my MoveShip script
using UnityEngine;
using System.Collections;
public class MoveShip : MonoBehaviour {
[HideInInspector]
public GameObject[] waypoints;
private int currentWaypoint = 0;
private float lastWaypointSwitchTime;
public float speed = 1.0f;
public Vector3 Velocity;
public Vector3 MoveDirection;
public Vector3 Target;
public Vector3 endPointDirection;
// Use this for initialization
void Start () {
lastWaypointSwitchTime = Time.time;
}
// Update is called once per frame
void Update () {
Vector3 startPosition = waypoints[currentWaypoint].transform.position;
Vector3 endPosition = waypoints[currentWaypoint + 1].transform.position;
float pathLength = Vector3.Distance(startPosition, endPosition);
float totalTimeForPath = pathLength / speed;
float currentTimeOnPath = Time.time - lastWaypointSwitchTime;
gameObject.transform.position = Vector3.Slerp(startPosition, endPosition, currentTimeOnPath / totalTimeForPath);
if (gameObject.transform.position.Equals(endPosition))
{
if (currentWaypoint < waypoints.Length - 2)
{
currentWaypoint++;
lastWaypointSwitchTime = Time.time;
}
else
{
return;
}
}
transform.LookAt(endPosition);
//gameObject.transform.position = Vector3.Slerp(startPosition, endPosition, currentTimeOnPath / totalTimeForPath);
//transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, currentTimeOnPath / totalTimeForPath);
}
}