Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How would I add 'jump' functionality to this script?

Hello, everyone. I have been working on a Third Person Character Controller, I have most of the functionality there thanks to some great tutorials (Brackeys and Nicky B.) and the help I have found online. (Image showing the Player Controller so far, below):

I used the Third Person Controller script found in Brackey's own video at https://www.youtube.com/watch?v=4HpC--2iowE. And now I am trying add the functionality of jumping to this controller. I looked online and found this code: (The code is in C#)   

    // The variables required.
    public float jumpForce = 5f;
    public float speed = 4f;
    private float gravity = 9.807f;
    private float verticalVelocity;
    bool isJumping = Input.GetKey("space"); 
   
    // If the player presses the 'Spacebar' then Jump!
    Vector3 movement = new Vector3(horizontalInput, 0f, verticalInput);
    movement = Vector3.ClampMagnitude(movement, speed);
    if (controller.isGrounded)
    {
      verticalVelocity = -gravity * Time.deltaTime;
      if (isJumping)
      {
        verticalVelocity = jumpForce;
      }
    } else
    {
      verticalVelocity -= gravity * Time.deltaTime;
    }

    heading.y = verticalVelocity; // apples gravity;

    movement = transform.TransformDirection(movement);
    controller.Move(movement * Time.deltaTime);

But, even after adding this, when I press the spacebar (the chosen key for jumping). The character won't do anything. Unless of course I got something wrong. You see this is what I typed (above) since my script worked slightly differently, the code they had looked like this:

         public float jumpForce = 10f;
         public float speed = 6f;

         private float gravity = 14f;
         private float verticalVelocity;         
        
         float deltaX = Input.GetAxis("Horizontal") * speed;
         float deltaZ = Input.GetAxis("Vertical") * speed;
 
         Vector3 movement = new Vector3(deltaX, 0, deltaZ);
         movement = Vector3.ClampMagnitude(movement, speed); //limits speed
 
         if (controller.isGrounded)
         {
             verticalVelocity = -gravity * Time.deltaTime;
             if (Input.GetButtonDown("Jump"))
             {
                 verticalVelocity = jumpForce;
             }
         }
         else
         {
             verticalVelocity -= gravity * Time.deltaTime;
         }
 
         movement.y = verticalVelocity; //applies gravity
 
         movement = transform.TransformDirection(movement);
         controller.Move(movement * Time.deltaTime);

I'm not sure if I am doing something wrong or not. Any help with this would be gladly appreciated. The attached files are the entire scripts talked about above in "*.txt" format.

Kind regards,

-Johnny

Best Answer

Sign In or Register to comment.