Jump Script

I am trying to make a very simple 3D plat-former with side to side movement and jumping; however, nothing seems to work when it comes to jumping. This code would work just fine if it weren’t for the, roughly, one-in-three chance of launching way to high in the air. I searched ideas for jump scripts and saw that other people have had this same problem but I never saw a solution. Can anyone help?

using UnityEngine;
using System.Collections;

public class playerMove : MonoBehaviour {

    public float jump;
    public float speed;
   
    Rigidbody rb;
   
    // Use this for initialization
    void Start () {
       
        rb = GetComponent<Rigidbody>();
       
    }
   
    // Update is called once per frame
    void FixedUpdate () {
       
       
        if (Input.GetKey("right"))
        {

            rb.AddForce(speed * Time.deltaTime, 0, 0);

        }

        if (Input.GetKey("left"))
        {

            rb.AddForce(-speed * Time.deltaTime, 0, 0);

        }

        if (Input.GetKeyDown("up"))
        {
            rb.AddForce(0, jump, 0);
        }
    }
}

Thanks for any and all help.

Can anyone help?

Have you tried using a stored vector???

This works for me…

rigidbody.AddForce(Vector3.up * step, ForceMode.Impulse);

Unfortunately, that isn’t working.

Why not? Does step have a value? Are you assigning the correct rigidbody? Is your rigidbody kinematic? It’s a very simple application of code that does work. I use it frequently.

It works just fine, but it doesn’t solve the problem of it jump way to high every few jumps.

You have no grounded check. You’re gonna need a raycast to check if your character is grounded before jumping again.

Or set the velocity to zero.

I intend to do that, but I am letting the ball fully land and sit on the ground before jumping again.

bump

According to this GetKeydown should be called from Update. FixedUpdate and Update run at different times, and rates. Maybe this is your issue?

2 Likes

Thank you, Korno!!

It now works without flying into space every few times.

Youre welcome, by the way you should keep your AddForce in FixedUpdate as thats the place for all physics stuff. Best to set a flag in Update to tell FixedUpdate to jump, then reset that flag in FixedUpdate after it has done the jump.

I don’t know how to tell FixedUpdate to do something from inside Update; could you give an example?

you cant do it inside update,
Fixedupdate will run at its own speed.

  • void Update()
  • {
    • }
  • void FixedUpdate()
  • {
    • }
void Update() {
     if(Input.GetButtonDown("Jump"){
          hasJumped = true;
     }
}

void FixedUpdate() {
     if(hasJumped){
          //Do something while jumping
     }
     If(isGrounded){
          hasJumped = false;
     }
}

Thank you