Smooth Object Movement

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:

if(Zombie.GetComponent(levelName).legalUp()){

			Zombie.transform.position.z += 2.0;

			}

This works fine, however it moves it immediately. I want to have it move smoothly. (Eventually I want a Zombie animation to walk forwards).

I tried making an animation that does this, but it uses absolute positions, and I for example I want to be able to move right, then right again.

Any ideas on the best course of action to take here? Can animations somehow get variables or can they only use absolute references in Unity?

Thanks!

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
  }

Try this:
http://unity3d.com/support/documentation/ScriptReference/Mathf.Lerp.html

Gist snippet here. It is a fully working example. The basic logic:

  1. Detect movement key
  2. Set target = position + movedistance
  3. set moving to true
  4. set direction to left/right/forward/backward as needed
  5. if moving is true:
  6. 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!)
  7. set position = target (don’t get off the grid! error adds up.)
  8. moving = false
  9. end if
  10. position = direction * (speed * Time.deltaTime)
  11. 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.