Search Unity

Moving forward only 1 unit per press [C#]

Discussion in 'Scripting' started by gie005, Jul 4, 2014.

  1. gie005

    gie005

    Joined:
    Aug 24, 2010
    Posts:
    81
    Hey all,
    I'm a noob in all this, so exuse my stupid code.

    if (Input.GetButtonDown("Forward")) {
    Debug.Log ("forward key pressed");
    transform.Translate(Vector3.forward * Time.deltaTime);
    transform.Translate(Vector3.up * Time.deltaTime, Space.World);
    }

    Currently I have that so that when Forward (defined in the Input Manager) is down, it moves you forward.
    This is my first project where I don't want to use any pre-written scripts from Unity or the Asset store.

    Although the code works, it only moves you forward a tiny bit and only once.
    How can I make it move you forward for as long as you hold down the button?
    The if statement I pasted above is in the default Update(); function, if it helps.

    Thanks!
    -Gie
     
  2. aniv

    aniv

    Joined:
    Jan 19, 2011
    Posts:
    135
    Use GetButton instead of GetButtonDown
     
    DevilZ1976 likes this.
  3. MischaWeerwag

    MischaWeerwag

    Joined:
    Jul 4, 2014
    Posts:
    9
  4. gie005

    gie005

    Joined:
    Aug 24, 2010
    Posts:
    81
    Thanks, that worked.
     
  5. gie005

    gie005

    Joined:
    Aug 24, 2010
    Posts:
    81
    @MischaWeerwag I just made a float movementSpeed = 0.3f and then did
    transform.Translate(Vector3.forward * movementSpeed);

    Instead of: transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime); because when multiplied by Time.deltaTime, it was slower :p
     
  6. MischaWeerwag

    MischaWeerwag

    Joined:
    Jul 4, 2014
    Posts:
    9
    Always multiply with deltatime also, otherwise your movement will not be consitent when framerate changes.
    do: Vector3.forward * speed * deltatime ALWAYS!
     
  7. gie005

    gie005

    Joined:
    Aug 24, 2010
    Posts:
    81
    Aaah, alright. I'll just turn up movementSpeed's value then.
     
  8. zDemonhunter99

    zDemonhunter99

    Joined:
    Apr 23, 2014
    Posts:
    478
    When you're going to move a object in the Update function, it is always safe and advisable to multiply it by Time.Deltatime.
     
  9. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483

    Multiplying by deltaTime is needed to allow for frame rate independent movement.
    e.g.
    Framerate drops to 30fps.
    Your movement code translates in a direction by movementSpeed PER FRAME
    So if movement speed is 1, you will translate 30 Units in 1 second
    But if your framerate fluctuated, to say 25,
    then 1 input of the same movement will only move 25 Units in 1 second.

    Deltatime is basically the difference in time it took to complete the current frame from the last, therefore, using this in your calculation in movement, it will multiply the difference so your speed will remain consistent