Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

2D Controller scripts...which one is better?

Discussion in '2D' started by G0DHAND, Nov 29, 2015.

  1. G0DHAND

    G0DHAND

    Joined:
    Nov 29, 2015
    Posts:
    2
    Hey guys. I'm just wondering what's the difference between these two C# script for 2d player movement.

    The first one uses the horizontal Axis:

    void Start ()
    {
    rigid = GetComponent <Rigidbody2D> ();
    anim = GetComponent <Animator> ();
    }

    void FixedUpdate()
    {
    float move = Input.GetAxis ("Horizontal");
    rigid.velocity = new Vector2 (move * moveSpeed, rigid.velocity.y);
    }

    while the second one uses KeyCode:

    if (Input.GetKey(KeyCode.D))
    rigid.velocity = new Vector2 (moveSpeed, rigid.velocity.y);

    if (Input.GetKey(KeyCode.A))
    rigid.velocity = new Vector2 (-moveSpeed, rigid.velocity.y);



    is there any difference between those two? is one better than the other?
    Thanks.
     
  2. LiberLogic969

    LiberLogic969

    Joined:
    Jun 29, 2014
    Posts:
    138
    The difference between the two is that Input.GetAxis(...) pretty much simulates the way thumb-sticks function. It will start at 0.0f and if for example you press the D key it will gradually increase from 0.0f to 1.0f and pressing the A key it will go from 0.0f to -1.0f. This will affect your movement by giving it a delay to build up to its max speed based on how long the key is held down, while using Input.GetKey() like in your second example will instantly cause your character to be at max speed when you press the desired movement key.

    If you go to Edit -> Project Settings -> Input in the Unity Editor you can set up your own custom axis for your desired inputs. The default Unity "Horizontal" axis is set up so the negative button is the A key and positive button is the D key (and a few other alternative keys and the left joysticks x axis).

    here is a useful link that does a better job explaining things than i just did :p

     
    theANMATOR2b likes this.
  3. G0DHAND

    G0DHAND

    Joined:
    Nov 29, 2015
    Posts:
    2
    Thanks a bunch. :)
    Aside from that, are there no more difference?
    I've tried both method and the acceleration speed,is somewhat different, is barely noticeable.

    Thanks