Search Unity

Player Controls in 2D game

Discussion in '2D' started by tonycsharks, Mar 15, 2018.

  1. tonycsharks

    tonycsharks

    Joined:
    Dec 31, 2015
    Posts:
    27
    Hi,

    I'm relatively new to Unity 2D. I'm doing a game which has player controls similar to those in the video given below. Can someone please help me how to do this? The player moves similar to the character in that game but with some differences. So I need to know how this kind of movement is acheived in Uunity2d.

     
  2. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Well it seems like there are two pre-defined x locations that these objects can move in, so really all you have to do is just make these objects switch between these two locations depending on when an input is held down. Something like:

    Code (CSharp):
    1.  
    2. public class Player : MonoBehavior {
    3.    public float minX;
    4.    public float maxX;
    5.  
    6.    void Update() {
    7.       if(Input.GetButton("some input") {
    8.          transform.position = new Vector2(maxX, transform.position.y);
    9.       }
    10.       else {
    11.          transform.position = new Vector2(minX, transform.position.y);
    12.       }
    13.    }
    14. }
    15.  
    This will snap the object to these positions, however. If you want smooth movement like in the video, you can use Vector2.Lerp when changing the x position of the object.

    If you aren't sure what is happening here though, then I'd recommend taking a look at https://unity3d.com/learn if you haven't already. It has some very useful information for Unity beginners, or those who just need refreshers.
     
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    You can, but you'll probably do it wrong. ;) Lerp is actually a little hard to use for this sort of thing. I'd recommend instead you just add a property for your target position, which you snap left/right based on inputs as shown above, and then use Vector2.MoveTowards to move your current position towards the target on every frame.

    Fully agree!
     
    Vryken likes this.
  4. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Didn't even know this method existed. Thanks.
     
  5. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    Sure thing — also check out Mathf.MoveTowards, Mathf.MoveTowardsAngle, and Quaternion.RotateTowards. Super handy!