- Home /
Smooth jump script?
I'm creating a 2d pixel art game and have been trying to create a smooth jumping script for my character, but it always ends up inconsistent or unrealistic.
So far, this is what I have:
Attached to my groundcheck GameObject is this script:
void OnTriggerEnter2D(Collider2D col) {
if (col.tag == "ground") {
movement.grounded = true; }
}
void OnTriggerStay2D(Collider2D col)
{
if (col.tag == "ground") {
movement.grounded = true;
}
}
void OnTriggerExit2D(Collider2D col)
{
if (col.tag == "ground") {
movement.grounded = false;
}
}
My groundCheck gameobject is attached to my player, with a boxcollider2d set to trigger that sits just below his feet. With grounded referencing to my grounded bool in my playerControl script.
Part of my PlayerControler script (attached to my character):
if (Input.GetKey (KeyCode.Space) && grounded) {
rb2d.AddForce(Vector2.up * speed);
control.SetBool ("jump", true); //play jump animation
} else {
control.SetBool ("jump", false); //stop jump animation
}
The problem is, jumping is inconsistent, sometimes he will jump high, sometimes he will jump not so high. Also, when consecutively jumping, it gets even worse.
If you have any suggestions or edits to this script, or a whole new way I can approach jumping, that would help me a lot. Thanks!
Answer by Merrick20 · Sep 19, 2017 at 09:15 PM
Have you tried using rb2d.velocity instead of AddForce?
Add Force does that it adds force gradually. And since you asked your script to do that while grounded. Once off the ground it stops adding force.
If I were you I would use something like this:
public float jumpVelocity;
if (isGronded)
{
myBody.velocity += jumpVelocity * Vector2.up;
}
That way when you press the jump key the velocity of the jump goes stright to the amount you want and you can regulate it whit the jumpVelocity float via Inspector.
Your answer
Follow this Question
Related Questions
Slime script? 1 Answer
How to I put a speed limit on my character's movement? 1 Answer
The Camera is facing backwards of the Character 1 Answer
Question about moving an object technique 3 Answers
Player Sliding without any Input 2 Answers