Search Unity

Infinite runner motion controller

Discussion in 'Scripting' started by SeanKilleen, Mar 3, 2015.

  1. SeanKilleen

    SeanKilleen

    Joined:
    Jul 17, 2013
    Posts:
    6
    Hi All,

    I am new to unity and new to the forum. I have run into an issue so i hope you can help me.
    Firstly, I am a software developer by profession so I can program but am new to 3d Maths an the unity engine.

    I am trying to make another subway surfer style infinite runer and jsut can't get the controls to work properly.

    What i would like to do is have 3 lanes and each time the user presses the left or right arrow the player will move into the relevant lane. As it stands, I have to keep my finger on the arrow for the player to move the correct distance. If I let go the player will stop between the lanes.

    Can anyone see an obvious fault in the below code?

    Any help is greatly appreciated.
     

    Attached Files:

  2. Kogar

    Kogar

    Joined:
    Jun 27, 2013
    Posts:
    80
    The code has a nice structure for the beginning. Instead of having two variables for left and right i would use one position variable lanePosition(enum or int: -1, 0, 1)
    Then it is easier to lock/switch onto one lane after a keypress. Just have to check if you are at a border value after a keypress and then keep the border value.

    Currently you have left and right that only get activated when you press the corresponding arrows. But nothing that sets a variable for center lane or keeps your variable after the key is released.
    Code (csharp):
    1. bool right = Input.GetKeyDown (KeyCode.RightArrow);
    2.      bool left = Input.GetKeyDown (KeyCode.LeftArrow);
    So instead of these two bools increase/decrease the variable on the corresponding key.
    for example
    Code (csharp):
    1.  if(Input.GetKeyDown (KeyCode.RightArrow))
    2. {
    3. if(lanePosition+1<=1) lanePosition++;
    4. }
    then instead of having to write multiple newPositions for left/center/right
    Code (csharp):
    1. float newPosition = Mathf.SmoothDamp(transform.position.x, pathRight.x, ref xVelocity, smoothTime);
    you can write something like
    Code (csharp):
    1. float newPosition = Mathf.SmoothDamp(transform.position.x, lanePosition*2.0f, ref xVelocity, smoothTime);
    and don't have to differentiate your paths with UpdatePaths()
     
    SeanKilleen likes this.
  3. SeanKilleen

    SeanKilleen

    Joined:
    Jul 17, 2013
    Posts:
    6
    Thanks Kogar for the help. The problem was that the control flow needed to be in the "if" block for the movement to continue. A valuable lesson learned. :)