- Home /
Making a player jump, getting random results
Hi, I have written a function in my player controller to make the character jump, however I seem to get pretty random results like every 3rd or 4th jump seems to be higher or sometimes it barely jumps at all.
Have I made an error in assuming that rigidbody.addforce was the way to go here?
My player is a 2d plane that has a rigidbody with gravity.
I have variables assigned on the player to control this
 var playerOneJumpRate = 1.0;        //Players time between jumps
 var playerOneJumpPower = 600;        //Players Jump Power
 var playerOneControlJump= ",";        //Player Controls (re-mappable)
I also have the following control function on the player
 // This function controls the players jump - makes the player wait to be able to jump again
 function jumpTime() 
 
 {
     while (true) 
     {
         if (Input.GetKeyDown (GameObject.Find("GameObjectPlayerOne").GetComponent(ScriptPlayerOneStats).playerOneControlJump)) {
         rigidbody.AddForce (Vector3.up * GameObject.Find("GameObjectPlayerOne").GetComponent(ScriptPlayerOneStats).playerOneJumpPower);
         yield WaitForSeconds(playerOneStats.playerOneJumpRate);
     } 
         else 
             {
                 yield;
             }
     }
     
 }
Answer by IvovdMarel · Jul 09, 2014 at 04:44 PM
Rather than adding force, you can directly set the velocity. This way, the jump height is not dependent on the characters current force. (e.g. if the character is falling fast, a jump with AddForce would only reduce his falling speed, not actually jump)
Answer by NerdRageStudios · Jul 09, 2014 at 05:35 PM
Aaah that makes sense, I shall try to have a look at that now, thanks for the swift reply :)
Sir, you are indeed a legend and that worked perfectly, thank you so much!
Here is my updated code:
 // This function controls the players jump - makes the player wait to be able to jump again
 function jumpTime() 
 
 {
     while (true) 
     {
         if (Input.Get$$anonymous$$eyDown (GameObject.Find("GameObjectPlayerOne").GetComponent(ScriptPlayerOneStats).playerOneControlJump)) {
         rigidbody.velocity = Vector3(0,GameObject.Find("GameObjectPlayerOne").GetComponent(ScriptPlayerOneStats).playerOneJumpPower,0);
         yield WaitForSeconds(playerOneStats.playerOneJumpRate);
     } 
         else 
             {
                 yield;
             }
     }
     
 }
Your answer
 
 
             Follow this Question
Related Questions
Jump off the edge of the object 1 Answer
jump on collision weird behaviour 2 Answers
What's wrong with this script? 4 Answers
How do I stop an object from jumping VERY high at first? 1 Answer
Change rigidbody's jumping speed 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                