- Home /
i want to do a auto moving objects
function FixedUpdate() {
// 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
Answer by syclamoth · Dec 19, 2011 at 06:44 AM
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; } }
Isit somethings wrong with the script,it cant work for me T_T,althought i have find another way but,i want to solve this script
Sorry, I forgot a bracket there. It's not really that hard an error to pick up.
Answer by wenhua · Dec 20, 2011 at 06:47 AM
i try to copy and paste in but why these error or somethings with this
No approprite version of 'UnityEngine.MonoBehaviour.StartCoroutine'for the argument list '(void)' was found.
was there anythings need to change or what?