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

Why isn't my character jumping?

Discussion in 'Scripting' started by SaamBell, Aug 5, 2015.

  1. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Anyone have any idea why my jump function isn't working for my vehicle? I hammer the space button and it just won't do anything :')
    And yes I have attached the rigidbody of the car to the slot

    Code (CSharp):
    1. public class vehicleController : MonoBehaviour {
    2.  
    3.  
    4.  
    5.     public float carSpeed;
    6.     public float maxPos = 3.6f;
    7.     public bool hasAddedSpeed = false;
    8.     public uiManager ui;
    9.     public GameObject car;
    10.     Vector3 position;
    11.     public Rigidbody rb;
    12.     public int jumpSpeed;
    13.  
    14.  
    15.  
    16.  
    17.  
    18.  
    19.     void Start ()
    20.     {
    21.         //ui = GetComponent<uiManager> ();
    22.         position = transform.position;
    23.         rb = GetComponent <Rigidbody>();
    24.    
    25.    
    26.     }
    27.    
    28.     void Update ()
    29.     {
    30.         if(!hasAddedSpeed)
    31.         {
    32.             if(ui.score >= 10)
    33.             {
    34.                 carSpeed = carSpeed + 2;
    35.                 hasAddedSpeed = true;
    36.             }
    37.  
    38.         }
    39.  
    40.         position.x += Input.GetAxis ("Horizontal") * carSpeed * Time.deltaTime;
    41.         position.x = Mathf.Clamp (position.x,-maxPos,maxPos);
    42.  
    43.  
    44.         if (Input.GetKeyDown(KeyCode.Space))
    45.         {
    46.             rb.AddForce(0,10,0 * jumpSpeed);
    47.         }
    48.  
    49.  
    50.         transform.position = position;
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    two problems,

    you're doing
    Code (csharp):
    1.  
    2. 0* jumpSpeed
    3.  
    0 times anything is 0, not sure what you're trying to do there but thats not going to help.

    the default forcemode is "Force", which is force applied over time, but GetKeyDown only fires in the one frame where the key is pressed. So you're only ever going to get a single frame's worth of force applied, which is peanuts.

    Try ForceMode.Impulse, all the force applied in one go

    http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
    http://docs.unity3d.com/ScriptReference/ForceMode.Impulse.html
     
  3. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Well I tried what you said

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.Space))
    2.         {
    3.             rb.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
    4.         }
    5.  
    6.  
    7.         transform.position = position;
    8.  
    Jumpspeed has been set to 10 in the inspector but still, nothing/:
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    You're explicitly setting the transform's position every frame, so of course you're not going to go anywhere.
     
  5. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Care to help a buddy out then :')? Guessing I'd have to make a bool or something?
     
  6. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Code (csharp):
    1.  
    2. transform.position = position;
    3.  
    You're explicitly setting the position every frame. Not really sure how else to help you. You need to either a) stop doing that or b) set your position's y variable equal to the current height of your jump.
     
  7. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    To clarify what GroZZler is saying.

    You are using the rigidbody to add a force for your jump. Then you just ignore what the rigid body is doing by reseting the position of the game object directly.

    A couple of things here:
    1. You shouldn't be using AddForce in update. It should be in FixedUpdate as its related to physics. You do need to keep your button check in Update though - use a bool to tell FixedUpdate to apply jump code.
    2. You are moving your car by directly setting the transform but also expect physics to just work. You probably shouldn't be doing both. RigidBody.MovePosition is a better method here as it will respect the collision settings of the rigidbody.
    This is not tested, but how about something like this:

    Code (CSharp):
    1. // Update is called once per frame
    2.     void Update () {
    3.         if(!hasAddedSpeed)
    4.         {
    5.             if(ui.score >= 10)
    6.             {
    7.                 carSpeed = carSpeed + 2;
    8.                 hasAddedSpeed = true;
    9.             }
    10.          
    11.         }
    12.         mAddJumpForce = Input.GetKeyDown (KeyCode.Space);
    13.  
    14.     }
    15.  
    16.  
    17.     void FixedUpdate(){
    18.         // jump or move
    19.         if (mAddJumpForce) {
    20.             rb.AddForce (Vector3.up * jumpSpeed, ForceMode.Impulse);
    21.             mAddJumpForce = false;
    22.         } else {
    23.             Vector3 position = rb.position;
    24.             position.x += Input.GetAxis ("Horizontal") * carSpeed * Time.deltaTime;
    25.             position.x = Mathf.Clamp (position.x,-maxPos,maxPos);
    26.             rb.MovePosition (position);
    27.         }
    28.  
    29.  
    30.     }
    Edit: Tested and it works but this allows you to double and tripple and quadroople jump. You will need to add some is grounded check to stop that.
     
    Last edited: Aug 6, 2015
  8. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    So I got a little bit more interested in this and wrote a version with a ground check to stop endless jumping. You will need to add the ui.score stuff back in as I deleted to allow this to compile in my test.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class driver : MonoBehaviour {
    5.  
    6.     // car settings
    7.     public int JumpSpeed;
    8.     public int CarSpeed=2;
    9.     public float MaxPos=3.6f;
    10.     public GameObject Car;
    11.    
    12.     // things for grounded check
    13.     // the layer(S) that have your ground in it - the care mustnt be in this layer
    14.     public LayerMask GroundLayers;
    15.     public float DistanceToCheck=0.5f;
    16.     protected bool mIsGrounded=true;
    17.    
    18.     // internal stuff
    19.     private Rigidbody mRB;
    20.     private bool mAddJumpForce=false;
    21.  
    22.     // Use this for initialization
    23.     void Start () {
    24.         mRB = GetComponent<Rigidbody> ();
    25.     }
    26.    
    27.     // Update is called once per frame
    28.     void Update () {
    29.  
    30.         mAddJumpForce = Input.GetKeyDown (KeyCode.Space) && mIsGrounded;
    31.  
    32.     }
    33.  
    34.  
    35.     void FixedUpdate(){
    36.         // jump or move
    37.         if (mAddJumpForce) {
    38.             mRB.AddForce (Vector3.up * JumpSpeed, ForceMode.Impulse);
    39.             mAddJumpForce = false;
    40.         } else {
    41.             Vector3 _position = mRB.position;
    42.             _position.x += Input.GetAxis ("Horizontal") * CarSpeed * Time.deltaTime;
    43.             _position.x = Mathf.Clamp (_position.x,-MaxPos,MaxPos);
    44.             mRB.MovePosition (_position);
    45.         }
    46.         mIsGrounded = Physics.Raycast (mRB.position, -gameObject.transform.up, DistanceToCheck, GroundLayers);
    47.     }
    48. }
    49.  
     
  9. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Done everything you said and created a new layer called Ground and attached it to my ground object. The car is not in this layer and is on the "default layer" Even still however the car is just refusing to do anything when i try and make it jump. Might this have something to do with the box collider on the vehicle?
    Here's the code anyway in case i overlooked anything! :)


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4.  
    5. public class vehicleController : MonoBehaviour {
    6.  
    7.  
    8.     //car settings
    9.     public float carSpeed;
    10.     public float maxPos = 3.6f;
    11.     public bool hasAddedSpeed = false;
    12.     public uiManager ui;
    13.     Vector3 position;
    14.  
    15.     public int jumpSpeed;
    16.  
    17.     //things for grounded check
    18.     public LayerMask GroundLayers;
    19.     public float DistanceToCheck= 0.5f;
    20.     protected bool mIsGrounded= true;
    21.  
    22.     //internal stuff
    23.     private Rigidbody mRB;
    24.     private bool mAddJumpForce = false;
    25.  
    26.  
    27.  
    28.  
    29.  
    30.  
    31.  
    32.     void Start ()
    33.     {
    34.         //ui = GetComponent<uiManager> ();
    35.         position = transform.position;
    36.         mRB = GetComponent<Rigidbody>();
    37.    
    38.    
    39.     }
    40.    
    41.     void Update ()
    42.     {
    43.         if(!hasAddedSpeed)
    44.         {
    45.             if(ui.score >= 10)
    46.             {
    47.                 carSpeed = carSpeed + 2;
    48.                 hasAddedSpeed = true;
    49.             }
    50.  
    51.         }
    52.  
    53.         position.x += Input.GetAxis ("Horizontal") * carSpeed * Time.deltaTime;
    54.         position.x = Mathf.Clamp (position.x,-maxPos,maxPos);
    55.  
    56.  
    57.         mAddJumpForce = Input.GetKeyDown (KeyCode.Space);
    58.  
    59.  
    60.         transform.position = position;
    61.  
    62.  
    63.  
    64.  
    65.  
    66.  
    67.         }
    68.  
    69.     void FixedUpdate()
    70.     // jump or move
    71.     {
    72.         if (mAddJumpForce)
    73.         {
    74.             mRB.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
    75.             mAddJumpForce = false;
    76.         } else {
    77.             Vector3 _position = mRB.position;
    78.             _position.x += Input.GetAxis ("Horizontal") * carSpeed * Time.deltaTime;
    79.             _position.x = Mathf.Clamp (_position.x,-maxPos,maxPos);
    80.             mRB.MovePosition (_position);
    81.         }
    82.         mIsGrounded = Physics.Raycast (mRB.position, -gameObject.transform.up, DistanceToCheck, GroundLayers);
    83.     }
    84.  
    85.  
    86.  
    87.  
    88.  
    89.  
    90.  
    91.  
    92.         void OnCollisionEnter(Collision col)
    93.         {
    94.             if(col.gameObject.tag == "Enemy Car")
    95.  
    96.                 ui.Dead();
    97.                
    98.  
    99.                
    100.         }
    101.     }
    102.  
     
  10. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    Seems like you have mixed the code with your version, and left a lot of the old problems in it. Use this, exactly as it is, I have merged your stuff into it:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent(typeof(Rigidbody))]
    5. public class driver : MonoBehaviour {
    6.  
    7.  
    8.     #region Variables
    9.     // character settings
    10.     public int JumpSpeed=2;
    11.     public int CharSpeed=2;
    12.     public float MaxHorizontalMove=3.6f;
    13.  
    14.     // things for grounded check
    15.     // the layer(S) that have your ground in it - the care mustnt be in this layer
    16.     public LayerMask GroundLayers;
    17.     public float DistanceToCheck=0.5f;
    18.     protected bool mIsGrounded=true;
    19.  
    20.     // internal stuff
    21.     private Rigidbody mRB;
    22.     private bool mAddJumpForce=false;
    23.     private bool hasAddedSpeed=false;:
    24. public uiManager ui;
    25.     #endregion
    26.  
    27.  
    28.     #region Unity Events
    29.     // Use this for initialization
    30.     void Start () {
    31.         mRB = GetComponent<Rigidbody> ();
    32.     }
    33.  
    34.     // Update is called once per frame
    35.     void Update () {
    36.         if(!hasAddedSpeed)
    37.         {
    38.             if(ui.score >= 10)
    39.             {
    40.                 CarSpeed = CarSpeed + 2;
    41.                 hasAddedSpeed = true;
    42.             }
    43.          
    44.         }
    45.         mAddJumpForce = Input.GetKeyDown (KeyCode.Space) && mIsGrounded;
    46.     }
    47.  
    48.  
    49.     void FixedUpdate(){
    50.         // jump or move
    51.         if (mAddJumpForce) {
    52.             mRB.AddForce (Vector3.up * JumpSpeed, ForceMode.Impulse);
    53.             mAddJumpForce = false;
    54.         } else {
    55.             Vector3 _position = mRB.position;
    56.             _position.x += Input.GetAxis ("Horizontal") * CharSpeed * Time.deltaTime;
    57.             _position.x = Mathf.Clamp (_position.x,-MaxHorizontalMove,MaxHorizontalMove);
    58.             mRB.MovePosition (_position);
    59.         }
    60.         mIsGrounded = Physics.Raycast (mRB.position, -gameObject.transform.up, DistanceToCheck, GroundLayers);
    61.     }
    62.  
    63.     void OnCollisionEnter(Collision col)
    64.     {
    65.         if (col.gameObject.tag == "Enemy Car") {
    66.             ui.Dead ();
    67.         }
    68.     }
    69.     #endregion
    70. }
    71.  
     
  11. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Works pretty much perfectly! Thank you so much :')
    However there is one tiny issue where the vehicle hits the ground. On some occasions I can jump as soon as i high the ground (which is what I want) and something it takes a few seconds for me to be able to jump again which comes off as a little unresponsive in a fast paced game. Anyway I Can adjust the code to remedy this :)??
     
  12. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    That could be related to the value of DistanceToCheck. That is how far below the model it looks for ground. Try turning that value up a bit.
     
  13. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Tried a few different values and that doesn't seem to be a problem. There's still random delay hitting the jump button. Any other ideas ^-^?
     
  14. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Fixed! Changed from GetKeyDown to GetKey and changed the JumpSpeed to 5 and now it's working how I wanted. Thanks again :')!
     
  15. Korno

    Korno

    Joined:
    Oct 26, 2014
    Posts:
    518
    Glad to help!

    Yeah that happens because GetKeyDown will only return true in the one frame that it is pressed while GetKey just keeps returning true while that key is down.

    The problem happens when you start holding the key when you are not grounded expecting the jump to happen when you become grounded. But it will fail and GetKeyDown will be returning false.

    Nastly little bug!

    If you are interested, I turned this code into an endless runner component - with a few extra features - air movement on/of and the ability to move forward and backwards in the z direction as well. The MaxPositionOffset vecotors Y component has that value.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [RequireComponent(typeof(Rigidbody))]
    5. public class Driver : MonoBehaviour {
    6.  
    7.  
    8.     #region Variables
    9.     // character settings
    10.     public int JumpSpeed=10;
    11.     public int CharSpeed=2;
    12.     public Vector2 MaxPositionOffset = new Vector2(3.6f, 3.6f);
    13.     public bool AllowAirControl=true;
    14.  
    15.     // things for grounded check
    16.     // the layer(S) that have your ground in it - the care mustnt be in this layer
    17.     public LayerMask GroundLayers;
    18.     public float DistanceToCheck=0.5f;
    19.     protected bool mIsGrounded=true;
    20.    
    21.     // internal stuff
    22.     private Rigidbody mRB;
    23.     private bool mAddJumpForce=false;
    24.     #endregion
    25.  
    26.  
    27.     #region Unity Events
    28.     // Use this for initialization
    29.     void Start () {
    30.         mRB = GetComponent<Rigidbody> ();
    31.     }
    32.    
    33.     // Update is called once per frame
    34.     void Update () {
    35.         // is the button down and the character grounded? no air jumping here!
    36.         mAddJumpForce = Input.GetKey (KeyCode.Space) && mIsGrounded  && !mAddJumpForce;
    37.     }
    38.  
    39.  
    40.     void FixedUpdate(){
    41.         // jump or move this frame - although air moving is accepted
    42.         // we will onky do one "thing" this frame
    43.         if (mAddJumpForce) {
    44.             mRB.AddForce (Vector3.up * JumpSpeed, ForceMode.Impulse);
    45.             mAddJumpForce = false;
    46.         } else if(mIsGrounded || (!mIsGrounded && AllowAirControl)) {
    47.             // NOTE: this assumes the player is centered at the origin
    48.             // to change this you will have to modify the how the position is
    49.             // clamped (we are using exact values - not offsets)
    50.             Vector3 _position = mRB.position;
    51.             float _horizontal, _vertical;
    52.             _horizontal = Input.GetAxis("Horizontal");
    53.             _vertical = Input.GetAxis("Vertical");
    54.             if(!Mathf.Approximately(_horizontal,0.0f))
    55.             {
    56.                 _position.x = Mathf.Clamp(_position.x + (Input.GetAxis("Horizontal") * CharSpeed * Time.deltaTime),
    57.                                       -MaxPositionOffset.x, MaxPositionOffset.x);
    58.             }
    59.             if(!Mathf.Approximately(_vertical, 0.0f))
    60.             {
    61.                 _position.z = Mathf.Clamp(_position.z + (Input.GetAxis("Vertical") * CharSpeed * Time.deltaTime),
    62.                                       -MaxPositionOffset.y, MaxPositionOffset.y);
    63.             }
    64.             mRB.MovePosition (_position);
    65.         }
    66.         // it might be possible to limit this check, if you know that jumping is the only way that
    67.         // the player will leave the ground you could set mIsGrounded to false in the jump method
    68.         // and add an if around this to only execute when mIsGrounded is false. However, as a generic component
    69.         // we cannot make that assumption as other game effects may make the player jump.
    70.         mIsGrounded = Physics.Raycast (mRB.position, -gameObject.transform.up, DistanceToCheck, GroundLayers);
    71.     }
    72.  
    73.     void OnCollisionEnter(Collision col)
    74.     {
    75.     }
    76.     #endregion
    77. }
    78.  
     
  16. SaamBell

    SaamBell

    Joined:
    Mar 28, 2014
    Posts:
    128
    Thanks a lot for all the effort but right now I'm really happy with what I've got! Might be very useful for fellow users tho :')!
    I wish there was some way I could show you my progress besides screenshots since the webplayer Doesn't work anymore :(!