Search Unity

How to move object by "steps" controlling time?

Discussion in 'Scripting' started by xalex1200, Oct 9, 2015.

  1. xalex1200

    xalex1200

    Joined:
    Oct 8, 2015
    Posts:
    2
    Hi, I'm beggining with Unity and I have a problem with my project. I guess it must be a very stupid question but I havent found anything in the web and don't know what else I can try. I'll just paste the necessary code:

    Code (CSharp):
    1.     void walk() {
    2.         Vector3 plpos = player.transform.position;
    3.         plpos.z += 1;
    4.         player.transform.position = plpos;
    5.     }
    I have a surface that I'm using like a kind of chessboard. What I want is to move the player from cell to cell but not describing a linear trajectory. I just want it to appear in the next cell. The code I've pasted works, but now is when my problem appears. I want to call this function in void update(), but of course the player disappears in a blink. I've tried to use Time.deltatime in multiple ways, but the problem is that as I said, I don't want a linear trajectory, I just want that each second the player appears in the next cell and I don't know if deltatime is what I need.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    You can structure your Start() function as a coroutine and have it call walk() periodically , like so:

    Code (csharp):
    1. IEnumerator Start()
    2. {
    3.     float interval = 1.0f;    // how often to step
    4.     while( true)    // endless loop
    5.     {
    6.         // wait for an interval...
    7.         yield return new WaitForSeconds(interval);
    8.         walk();        // take one step
    9.     }
    10. }
    Make sure you do NOT take out the yield statement or else Unity will lock up with the abovecode.
     
    Kiwasi and xalex1200 like this.
  3. xalex1200

    xalex1200

    Joined:
    Oct 8, 2015
    Posts:
    2
    Thank you! works perfectly! I suspected this is what i needed, but I didn't know how to apply it to my case.