//Created by Neodrop
//neodrop@unity3d.ru
using UnityEngine;
//#pragma warning disable
public class MoveOnCurve : MonoBehaviour {
public GameObject curve;
public float speed = 1f, minDistanceToPoint = .1f, rotationDamping = 6f;
private Curve _curve;
public int currentCurvePoint = 0;
private Transform _target;
void Start () {
_curve = new Curve(curve);
_target = new GameObject("target").transform;
PositionOnStart();
}
void PositionOnStart()
{
//Set the initial cube position over the Curve Start point
transform.position = _curve.curvePoints[_curve.GetNearestCurveSmoothPoint(0)];
//Set the target object position in next curve point
_target.position = _curve.curvePoints[1];
transform.LookAt(_target);
}
void Update ()
{
if (currentCurvePoint == -1) return;
if (Vector3.Distance(transform.position, _target.position) < minDistanceToPoint)
{
currentCurvePoint++;
if (currentCurvePoint == _curve.curvePoints.Length)
{
currentCurvePoint = 0;
PositionOnStart();
}
else _target.position = _curve.curvePoints[currentCurvePoint];
}
// Smooth Look at target to smoothing movement
Quaternion rotation = Quaternion.LookRotation(_target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
// Move to target
transform.Translate(Vector3.forward*(Time.deltaTime*speed), Space.Self);
}
}