move a point along a line unity code example
Example: unity3d gameobject follow path
public class EnemyBehavior : MonoBehaviour{
public Path pathToFollow;
public int currentWayPointID = 0;
public float speed = 2;
public float reachDistance = 0.4f;
public float rotationSpeed = 5f;
float distance;
public bool useBezier = false;
public enum EnemyStates
{
ON_PATH,
IDLE
}
public EnemyStates enemyState;
public int enemyID;
void Update()
{
switch (enemyState)
{
case EnemyStates.ON_PATH:
MoveOnThePath(pathToFollow);
break;
case EnemyStates.IDLE:
break;
}
}
void MoveToFormation()
{
{
transform.eulerAngles = Vector3.zero;
enemyState = EnemyStates.IDLE;
}
}
void MoveOnThePath(Path path)
{
if (useBezier)
{
distance = Vector3.Distance(path.bezierObjList[currentWayPointID], transform.position);
transform.position = Vector3.MoveTowards(transform.position, path.bezierObjList[currentWayPointID], speed * Time.deltaTime);
var direction = path.bezierObjList[currentWayPointID] - transform.position;
if (direction != Vector3.zero)
{
direction.z = 0;
direction = direction.normalized;
var rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}
}
else
{
distance = Vector3.Distance(path.pathObjList[currentWayPointID].position, transform.position);
transform.position = Vector3.MoveTowards(transform.position, path.pathObjList[currentWayPointID].position, speed * Time.deltaTime);
var direction = path.pathObjList[currentWayPointID].position - transform.position;
if (direction != Vector3.zero)
{
direction.y = 0;
direction = direction.normalized;
var rotation = Quaternion.LookRotation(direction);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}
}
}}