Search Unity

[JS] Infinite runner script bug that needs smoothing out

Discussion in 'Scripting' started by suctioncup, Sep 17, 2012.

  1. suctioncup

    suctioncup

    Joined:
    May 19, 2012
    Posts:
    273
    Hello,

    Code (csharp):
    1. #pragma strict
    2.  
    3. var blocks : GameObject[];
    4. var lastBlock : Transform;
    5.  
    6. var delay : float = 2;
    7.  
    8. private var num : int;
    9. private var lastNum : int;
    10.  
    11. InvokeRepeating("Place",0,delay);
    12.  
    13. function Place()
    14. {
    15. Debug.Log(num);
    16. var block : GameObject;
    17.  
    18.     while(num == lastNum)
    19.     {
    20.     num = Random.Range(1,5);
    21.     }
    22.     lastNum = num;
    23.    
    24. block = blocks[num];
    25. block.transform.position.z = lastBlock.position.z + 2;
    26. lastBlock = block.transform;
    27. }
    Thats my infinite runner script - not amazing, but I am trying to get the basics down before I do anything different. The problem with this script is that sometimes big gaps appear between each separate block -- how do I fix this? Thanks.

    Currently this is applied to an empty in my scene, with 4 or so blocks at 0,0,0. These blocks are referenced in the array.

    I am a sort of advanced beginner, so please explain some complex theories a little dumbed down :)
     
    Last edited: Sep 17, 2012
  2. suctioncup

    suctioncup

    Joined:
    May 19, 2012
    Posts:
    273
    Sorry for bumping my own post, but I'm really struggling with this.
     
  3. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    First, arrays are zero-indexed, meaning you need a random number between (0, array.length-1).


    You're choosing a random block. What happens when you have this setup:

    [1][2][3][0] (0 is 'last' block)

    Then '3' is chosen - now you have this setup:

    [1][2][ ][0][3]
    Big gap between 2 and 0.

    You should either instantiate blocks, or only allow blocks to be chosen if they're already off screen.