Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Dumb question - making a player sprint by multiplying move speed

Discussion in 'Editor & General Support' started by MinuteMan_, Jan 31, 2023.

  1. MinuteMan_

    MinuteMan_

    Joined:
    Apr 15, 2017
    Posts:
    9
    Hi i'm very new to Unity, i used to fiddle around with it in high-school but i'm pretty much starting from the ground up again. I followed a youtube tutorial to create player movement. i wanted to upgrade the code by adding in a feature to allow running when holding down "shift". To do this, i input an "If function" into the void update. The rest of the code is running fine but it does not seem to be picking up my "If Input.GetButton.Down "Fire3"" code (i have bolded it).

    my code for the "shift-to-sprint" is as follows:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerController : MonoBehaviour
    {
    private float moveSpeed;
    public CharacterController controller;
    private Vector3 moveDirection;

    void Start () {

    controller = GetComponent<CharacterController>();
    moveSpeed = 10;

    }

    if (Input.GetButtonDown ("Fire3"))
    {

    moveSpeed = moveSpeed * 2;

    }
    else
    {
    moveSpeed = 10;
    }


    moveDirection = new Vector3(Input.GetAxis("Horizontal") * moveSpeed, 0f, Input.GetAxis("Vertical") *moveSpeed);

    if (Input.GetButtonDown ("Jump"))

    moveDirection.y = moveDirection.y + (Physics.gravity.y * gravityScale);

    {
    moveDirection.y = jumpForce;
    }

    controller.Move(moveDirection *Time.deltaTime);

    }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,893
    GetButtonDown
    is only true for the single exact frame in which you press the button.
    The very next frame, it will no longer be true, at which point the
    else
    block will run, setting your speed to 10. So you will only get ONE FRAME of sprint speed with this code.

    Perhaps you just want to use
    GetButton
    which will constantly return true during all frames in which the button is held down?

    As always this information can be found in the Unity scripting reference
    https://docs.unity3d.com/ScriptReference/Input.GetButtonDown.html
    https://docs.unity3d.com/ScriptReference/Input.GetButton.html
     
  3. MinuteMan_

    MinuteMan_

    Joined:
    Apr 15, 2017
    Posts:
    9
    i love you