Hi All, I’m trying to make a simple cube move at a set speed, pause when it reaches a certain point on its x-axis and then continue moving again. I’m trying to do yield wait for seconds but I could be very wrong, after searching the web I can’t seem to find out what I’m missing or doing wrong.
Perhaps an invoke function (I’m not familiar with those) would be better?
Here’s my code:
var amtToMove: float; //variable to edit the speed of the moving object
var enemySpeed: int;
var moveforward: boolean;
function Start(){
moveforward = true;
}
function Update () {
//Checks to see which operation to perform - move or stop
if(moveforward)
move();
else
stop();
}
function move(){
amtToMove = enemySpeed * Time.deltaTime;
transform.Translate(Vector3(-1, 0, 0) * amtToMove);
return;
}
function stop(){
if(transform.position.x <= -8){
Debug.Log("stop point");
yield WaitForSeconds(5);
moveforward = false;
return;
}
}
I think you just have your ordering wrong. I think you just want:
function Update() {
if (moveforward)
move();
else
stop();
}
function move() {
if (tranform.position.x <= 8)
moveforward = false;
else {
amtToMove = enemySpeed * Time.deltaTime;
transform.Translate(Vector3(-1, 0, 0) * amtToMove);
return;
}
}
function stop() {
Debug.Log ("Stop point");
yield WaitForSeconds(5);
moveforward = true;
return;
}
Edit: more to fix…
I believe your problem is when variables are being set and changed. Based on the description I changed where your flags are being set so it’s more logical.
As far as I know, ‘yield’ only works in a coroutine.
You can use the Invoke function to call a function after a set time though.
You might want something like this:
function Pause(){
if(!moveforward) return;
moveforward = false;
Invoke("Unpause",5);
}
function UnPause(){
moveforward = true;
}
Bear in mind also, that at the moment you only test the position in the stop function. It won’t know to go to the stop function until it’s tested what position it’s in, and is won’t test what position it’s in until it’s gone there. So you have to test the position in the update function or the move function.
Remember as well that after it’s stopped for a few seconds and is ready to start again, it will still have a position less than -8, and so will immediately pause again, and so will keep pausing and effectively never start, unless you add a variable to check whether you’ve already paused once, so you know not to pause again.
thanks for the answers, @slev’s answer worked but once it gets to the desired location and pauses it doesn’t move forward again. As you said @ferb a var boolean might do the trick.
I’m thinking I put the false statement in function stop and the true statement inside the else statement of function move. But I’m not sure how to approach this exactly, am I on the right track or am I completely misunderstanding how vars work?