- Home /
Problem with MoveToWaypoint
Hi! In my game I want my NPC move from one point to another and therefore I created the following script based on an example I found on the web. But the NPC is not having a uniform motion, and doesn't stop for a while when it reaches the target position as I wanted. He is always rotating and moving around the map. Also, appears the error: "Script error: Update () can not be a coroutine." Someone can help me solve this problem please?
var pointB : Vector3;
private var pointA : Vector3;
var moveSpeed : float = 10.0;
var waitTime : float = 5.0;
private var waitTimer : float;
//enum State {Waiting, Moving}
private var currentState : State;
function Start () {
pointA = transform.position;
currentState = State.Moving;
}
function Update () {
switch(currentState){
case State.Waiting:
Wait();
break;
case State.Moving:
if(transform.position==pointA)
MoveObject(transform, pointA, pointB, 3.0);
if(transform.position==pointB)
MoveObject(transform, pointB, pointA, 3.0);
break;
}
}
function MoveObject (thisTransform : Transform, startPos : Vector3, endPos : Vector3, time : float) {
var i = 0.0;
var rate = 1.0/time;
while (i < 1.0) {
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp(startPos, endPos, i);
thisTransform.LookAt(endPos);
//yield;
}
if(thisTransform.position == endPos)
currentState = State.Waiting;
}
function Wait() : void{
waitTimer += Time.deltaTime;
if(waitTimer > waitTime){
waitTimer = 0.0;
currentState = State.Moving;
}
}
You cannot put yield statements directly inside the function Update, at most you can call a function outside of the actual update that has Yield in it.
Thanks, I didn't know that. I fixed that, but its motion is the same: with a random motion around the map and not between two defined points linearly :S
Answer by g0tNoodles · Feb 13, 2013 at 10:46 PM
This is what I use for a simple waypoint script. Modify it how you see fit!
var waypoint : Transform[];
var speed : float = 20;
private var currentWaypoint : int;
var loop : boolean = true;
function Update () {
if(currentWaypoint < waypoint.length){
var target : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = target - transform.position;
var velocity = rigidbody.velocity;
if(moveDirection.magnitude < 1){
currentWaypoint++;
} else {
velocity = moveDirection.normalized * speed;
}
} else {
if(loop){
currentWaypoint = 0;
} else {
velocity = Vector3.zero;
}
}
rigidbody.velocity = velocity;
}
Your answer
Follow this Question
Related Questions
How to move an npc? 1 Answer
Making an NPC go up and down in UNITY 0 Answers
Moving model with animation 2 Answers