- Home /
Enemy can only move in one direction at a time using transform.Translate and Coroutines?
Hello again Unity community!
I'm trying to script an enemy rolling along the ground that occasionally hops up after two seconds. This means I want the enemy to continue moving left, but occasionally go up and down while still moving left. However, I cannot get the enemy to continue moving left while the hop occurs (meaning the enemy stops in its track when it moves up and down), and I think it has something to do with the yield Coroutine stopping the left movement.
Anyone have any ideas or leads how to work around this issue?
My current code is below.
function Start () {
while(true){
yield WaitForSeconds(3);
yield MoveObject.use.Translation(transform, Vector3.up * 3, 2, MoveType.Time);
yield MoveObject.use.Translation(transform, Vector3.down * 3, 2, MoveType.Time);
}
}
function Update () {
transform.Translate(Time.deltaTime * -3, 0, 0);
}
I'm not familiar with coroutines in JS, but in C#, you don't put yield in front of the commands that happen after the WaitForSeconds(). Just a thought to try removing those 2nd and 3rd yield's.
Answer by sabin22 · Sep 23, 2012 at 09:14 PM
Figured it out: I used the MoveObject custom function and it worked like a charm:
var DistanceBeforeHop : float;
var TumbleHopHeight : float;
var UnitsPerSecond : float;
var DistanceDuringHop : float;
function Start () {
while(true){
yield MoveObject.use.Translation(transform, Vector3(DistanceBeforeHop, 0, 0), UnitsPerSecond, MoveType.Speed);
yield MoveObject.use.Translation(transform, Vector3(DistanceDuringHop, TumbleHopHeight, 0), UnitsPerSecond, MoveType.Speed);
yield MoveObject.use.Translation(transform, Vector3(DistanceDuringHop, -TumbleHopHeight, 0), UnitsPerSecond, MoveType.Speed);
}
}
function Update () {
}
Thanks for answering anyway, justinl!