Search Unity

jump script not working please help

Discussion in 'Getting Started' started by addtheflame, Feb 26, 2023.

  1. addtheflame

    addtheflame

    Joined:
    Feb 5, 2023
    Posts:
    1
    using UnityEngine;

    public class Jump : MonoBehaviour
    {
    public float jump = 300f;
    public Rigidbody rb;
    // Update is called once per frame
    void OnCollisionEnter(UnityEngine.Collision collisionInfo)
    {
    if (collisionInfo.collider.tag == "Ground" && (Input.GetKey("x")))
    {
    rb.AddForce(Vector3.up * jump * Time.deltaTime);
    }

    }
    }
     
  2. RichAllen2023

    RichAllen2023

    Joined:
    Jul 19, 2016
    Posts:
    1,026
    1) Use CODE tags
    2) Your code is riddled with typos
     
  3. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    490
  4. TylerJay-B

    TylerJay-B

    Joined:
    Dec 29, 2018
    Posts:
    18
    OnCollisionEnter is called only once the object enters the collision, you're better off using events or checking for input in update and then calling your jump method

    something like the following should work

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Jump : MonoBehaviour
    4. {
    5.     [SerializeField] private float jumpForce = 300f;
    6.     [SerializeField] private Rigidbody rb;
    7.  
    8.     [SerializeField] private KeyCode jumpKey = KeyCode.X;
    9.  
    10.     public bool IsGrounded
    11.     {
    12.          get
    13.          {
    14.                // check if grounded here.
    15.                return false;
    16.          }
    17.     }
    18.  
    19.     private void Update()
    20.     {
    21.       if (Input.GetKeyDown(jumpKey))
    22.       {
    23.            // should jump
    24.            TryJump();
    25.       }
    26.     }
    27.  
    28.     private void TryJump()
    29.     {
    30.          if (IsGrounded)
    31.          {
    32.               Jump();
    33.          }
    34.     }
    35.  
    36.     private void Jump()
    37.     {
    38.           rb.AddForce(jumpForce * Vector3.up, ForceMode.Impulse);
    39.     }
    40. }
     
  5. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    660
    I don't see an edit, and i don't see alot of typos at all...
     
  6. BABIA_GameStudio

    BABIA_GameStudio

    Joined:
    Mar 31, 2020
    Posts:
    497
    Care to point those out, as I can't see any. Except perhaps the use of "x" as the parameter of GetKey for the input they want - but that is not exactly "riddled with typos".