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

Need help with my code for making a ball jump

Discussion in 'Getting Started' started by Naifarer, Jul 24, 2020.

  1. Naifarer

    Naifarer

    Joined:
    Jul 24, 2020
    Posts:
    1
    Hi so i've started learning unity and i made a code that should make a ball jump and move but when i give a value to salto my ball goes out of the screen flying.
    This is the code:

    public class move : MonoBehaviour
    {

    public float forceValue;
    public float Salto;
    private Rigidbody rigidbody;
    void Start()
    {
    rigidbody = GetComponent<Rigidbody> ();
    }


    void Update()
    {
    if (Input.GetButtonDown("Jump") && Mathf.Abs(rigidbody.velocity.y) < 0.01f);
    rigidbody.AddForce(Vector3.up * Salto, ForceMode.Impulse);
    }

    public void FixedUpdate()
    {
    rigidbody.AddForce(new Vector3 (Input.GetAxis ("Horizontal"),
    0,
    Input.GetAxis("Vertical")) * forceValue);
    }
    }
     
    Last edited: Jul 24, 2020
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Try assigning Salto a smaller value, and/or setting the mass of the rigidbody to a higher value.

    You shouldn't call AddForce from Update by the way. It should be called in FixedUpdate, though you should still check for input in Update as you are doing.