// Move the character a bit each frame.
transform.position += transform.forward * .02;
// Destroy the character when it's out of view.
if (Vector3.Distance(Vector3.zero,transform.position) > 20);
transform.position -= transform.forward * .02;
}
i was working on this object where i need it to move 20 distance far away and make it auto move back to orignal places and repect the process which is 0-20 then 20-0 and continue…
But this code will move to 20 and stop there or somethings it will move all the way
can some 1 help me with it Thx
The object stops at the end because you are telling it to rapidly oscillate around the end point- you never tell it to stop moving, so it keeps moving forward and moving backwards the same amount every frame.
A better way to do this would use coroutines to manage the movement.
function Start()
{
StartCoroutine(MoveBetweenWaypoints(transform.position, transform.position + transform.forward * 20, 20));
}
function MoveBetweenWaypoints(start : Vector3, end : Vector3, patrolTime : float)
{
while(true)
{
GoToPoint(end, patrolTime);
GoToPoint(start, patrolTime);
}
}
function GoToPoint(target : Vector3, time : float)
{
var elapsedTime : float = 0;
var startPos : Vector3 = transform.position;
while(elapsedTime < time)
{
transform.position = Vector3.Lerp(startPos, target, time / elapsedTime);
elapedTime += Time.deltaTime;
yield;
}
}