Skip to content

Instantly share code, notes, and snippets.

@MuhammadFaizanKhan
Created December 14, 2017 07:40
Show Gist options
  • Save MuhammadFaizanKhan/074b3200a87d958135e865571c31e813 to your computer and use it in GitHub Desktop.
Save MuhammadFaizanKhan/074b3200a87d958135e865571c31e813 to your computer and use it in GitHub Desktop.
Move object on way points in unity3d
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectMovmentOnWayPoints : MonoBehaviour
{
#region Vars
public List<GameObject> movmentWayPoints;
public float moveSpeed = 2f;
[Tooltip("Beginning Wait Time")]
public float initialWait = 5;
[Tooltip("Wait time at every waypoint")]
public float waitAtEveryPoint = 3f;
public bool isLoop = true;
float distance;
private GameObject ship;
[Header("At after what distance move to next point")]
public float distnaceThreshold = 22;
#endregion Vars
void Start()
{
ship = this.gameObject;
StartCoroutine(MoveOnWayPoints());
if (movmentWayPoints.Count == 0)
{
Debug.LogWarning("There is no movment point, ship will not start to sail");
}
}
IEnumerator MoveOnWayPoints()
{
yield return new WaitForSeconds(initialWait); //inital wait
for (int i = 0; i < movmentWayPoints.Count; i = GetNewIndex(i))
{
yield return new WaitForSeconds(waitAtEveryPoint);//Wait at every point
GameObject movmentTarget = movmentWayPoints[i].gameObject;
Vector3 destinationDirection = movmentTarget.transform.position - ship.transform.position;
distance = Vector3.Distance(ship.transform.position, movmentTarget.transform.position);
while (distance > 22f)
{
Quaternion lookRotation = Quaternion.LookRotation(destinationDirection);
ship.transform.rotation = Quaternion.Lerp(ship.transform.rotation, lookRotation, Time.deltaTime * 2f);
ship.transform.Translate(new Vector3(0f, 0f, Time.deltaTime * moveSpeed));
distance = Vector3.Distance(ship.transform.position, movmentTarget.transform.position);
yield return new WaitForEndOfFrame();
}
}
}
int GetNewIndex(int lastIndex)
{
if (isLoop == true)
{
if (lastIndex >= movmentWayPoints.Count - 1)
{
lastIndex = 0;
}
else
{
lastIndex++;
}
return lastIndex;
}
else
{
return lastIndex++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment