Make a rigidbody Jump (global up)
Hi, I am attempting to make a rigid body jump upwards (global) The script which i have tried to use doesn't seem to work. All help is appreciated.
function Update(){
if (Input.GetKeyDown (KeyCode.Space)){
rigidbody.AddForce (0, 10, 0);
}
}
Answer by syclamoth · Dec 01, 2011 at 09:34 PM
First off, put that in FixedUpdate. Otherwise, try using this-
rigidbody.AddForce(new Vector3(0, 100, 0), ForceMode.Impulse);
It's possible that you just aren't seeing anything because the force is too low!
Thank you it works very well with these two lines of codes.
Answer by aldonaletto · Dec 01, 2011 at 09:38 PM
The easiest way is to set the rigidbody.velocity directly (you will not depend on the object mass):
var jumpSpeed: float = 8;
function Update(){ if (Input.GetKeyDown (KeyCode.Space)){ rigidbody.velocity += jumpSpeed * Vector3.up; } }
According to the docs you should not directly modify the velocity of a rigidbody as it creates weird results and unrealistic behaviour.
Yes: in this particular case, the unrealistic behaviour will be the rigidbody stopping its horizontal movement and jumping vertically. Actually, you can modify rigidbody.velocity directly without screwing up the physics as long as the current velocity is taken into account - that's what AddForce and other rigidbody functions do.
A better alternative in this case would be to add the vertical velocity like this:
rigidbody.velocity += Vector3.up * jumpSpeed;
This would preserve the current movement and simply add a vertical component.
Thanks for the comment - the answer has been edited.
No I was more talking about the fact that if you just add velocity to rigidbody, you are not "pushing" it up. So what happens is that gravity starts to compund and as soon as you stop applying the velocity, the object will shoot down. Don't get me wrong, it'll still works. Just commenting in case any one else runs into the issue.
Answer by XenoTracker · Apr 09, 2015 at 04:37 AM
Apparently this is the new AddForce thing
Public float jumpSpeed = 5f;//or whatever you want it to be
public Rigidbody rb; //and again, whatever you want to call it
void Start (){
rb = GetComponent <Rigidbody>();
}
Void FixedUpdate(){
if(Input.GetKey (KeyCode.Space)){
rb.AddForce(Vector3.up * jumpSpeed);
}
}
and in the inspector just drag the Player game object from the hierarchy to the rb slot in the script and you're good :3
Nothing new. Just there is no rigidbody shortcut any more so you need to link it with GetComponent like any other component now.
Your answer
Follow this Question
Related Questions
Later grab doesn't jump 0 Answers
Rigidbody Stop and jump 0 Answers
c# jumping isn't consistent, please help 0 Answers
Character stuck in ground/can't get character to jump 1 Answer