Hello. I am trying to move a box around on a 2D grid. Basically my game ends up taking a value and dependent on what it is it moves the block either right, left, up, or down by 2. (where right/left is x axis and up/down is z axis). I currently have been doing this:
As @syclamoth suggested, a coroutine is a good choice. The function below moves the Zombie object dx units in x and dz units in z:
var duration:float = 0.9; // duration of movement in seconds
var moving:boolean = false; // flag to indicate it's moving
function MoveZombie(dx: float, dz: float){
if (moving) return; // if already moving return
moving = true; // else set flag to signal it's moving now
var curPos = Zombie.transform.position;
var newPos = curPos + Vector3(dx, 0, dz); // calculate new position
for (var t: float = 0; t < 1;){
t += Time.deltaTime / duration; // advance t towards 1 a little step
Zombie.transform.position = Vector3.Lerp(curPos, newPos, t); // move
yield; // suspend execution till next frame
}
moving = false; // movement finished
}
Call MoveZombie with the desired displacement to move:
if (Zombie.GetComponent(levelName).legalUp()){
MoveZombie(0, 2); // move zombie 2 units ahead in z
}
Gist snippet here. It is a fully working example. The basic logic:
Detect movement key
Set target = position + movedistance
set moving to true
set direction to left/right/forward/backward as needed
if moving is true:
if (target-postition).magnitude < 0.001 (this is critical! never test for magnitude == 0 because that will hardly every happen due to floating point error!)
set position = target (don’t get off the grid! error adds up.)
moving = false
end if
position = direction * (speed * Time.deltaTime)
end if
In my example I have delta, speed, and movedistance as public so those values can be adjusted without having to fool with code.