Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Rigidbody and Gravity (Jumping)

Discussion in 'Scripting' started by Tacosaurus, Mar 17, 2015.

  1. Tacosaurus

    Tacosaurus

    Joined:
    Mar 5, 2015
    Posts:
    8
    Everything is working almost perfectly. The one problem I'm having is the way the jumping looks.
    Basically, if I hold down the Jump key, the jump looks right. But if I hold it and release it, I fall much faster than it looks like I should. Like gravity snaps into play the instant I take my finger off the jump key.
    Take a look at the code.
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Movement : MonoBehaviour {
    5.  
    6.     public float speed = 6.0f;
    7.     public float jumpSpeed = 8.0f;
    8.     private bool jump = false;
    9.     public float gravity = 10.0f;
    10.  
    11.     Vector3 moveDir = new Vector3();
    12.     public Rigidbody rb;
    13.  
    14.     // Use this for initialization
    15.     void Start () {
    16.        
    17.     }
    18.    
    19.     // Update is called once per frame
    20.     void Update () {
    21.         Move ();
    22.     }
    23.  
    24.     void Move(){
    25.         moveDir = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    26.         moveDir = transform.TransformDirection(moveDir);
    27.         moveDir = moveDir * speed;
    28.         if (Input.GetButton ("Jump")){
    29.             moveDir.y = jumpSpeed;
    30.         }
    31.         moveDir.y -= gravity * Time.deltaTime;
    32.         rb.MovePosition(transform.position + moveDir * Time.deltaTime);
    33.     }
    34. }
    Any tips or pointers are welcome!
     
  2. L-Tyrosine

    L-Tyrosine

    Joined:
    Apr 27, 2011
    Posts:
    305
  3. Tacosaurus

    Tacosaurus

    Joined:
    Mar 5, 2015
    Posts:
    8
    That's actually a much better idea. Thanks for the link too! It's very helpful.