- Home /
Why do I double jump? This isn't supposed to happen...
So I have this script, shown below: var moveSpeed : float = 0.1; private var IsGrounded = false; var JumpStrength : float = 5; private var animator;
function Start() {
animator = GetComponent("Animator");
}
function Update () {
gameObject.transform.Translate(Input.GetAxis("Horizontal") * moveSpeed, 0, 0);
if(Input.GetKey("a")) {
gameObject.transform.localScale.x = -1;
}else if( Input.GetKey("d") ){
gameObject.transform.localScale.x = 1;
}
if(Input.GetKey("a") || Input.GetKey("d")) {
animator.SetBool("running", true);
}else{
animator.SetBool("running", false);
}
if(Input.GetKeyDown("space") && IsGrounded) {
IsGrounded = false;
Jump();
}
}
function OnCollisionEnter2D(col : Collision2D) {
if(col.gameObject.tag == "Ground")
IsGrounded = true;
}
function Jump() {
IsGrounded = false;
gameObject.rigidbody2D.AddForce(Vector2.up * JumpStrength);
IsGrounded = false;
}
and whenever I hold either the A or D keys, and press space, I have the ability to double jump, which is not intended and is rather overpowered to add to my game. I assume there's something wrong with gameObject.transform.Translate(Input.GetAxis("Horizontal") * moveSpeed, 0, 0);
that doesn't like collisions. Is there any workaround or solution?
$$anonymous$$mhhh, I'm not sure using translate is the way to go indeed...
Can you try working this out using add force ins$$anonymous$$d ?
Answer by MarkPwns1 · Aug 27, 2014 at 02:40 PM
Finally! I've managed to fix it. The problem was exactly what you said, but when adding the OnCollisionExit2D didn't work, I just decided a more simple answer would be to just add a yield WaitForSeconds(0.1);
to the end of my Jump() method. Thank you anyway for your help!
Answer by kacyesp · Aug 27, 2014 at 03:45 AM
I think the problem might be that right after you set IsGrounded to false in your Jump() function, OnCollisionEnter2D sets the boolean back to true because you the ground is still colliding with your collider as you're taking off.
Can you try adding an OnCollisionExit2D function with the same code as your OnCollisionEnter2D function but instead of setting grounded to true, set it to false ?
Hmm, I did exactly as you said, but with no luck. Now the player can jump infinitely... All I really want is some 2D character controller on the asset store. Anyway, like I said, I assume it's a problem with line 4 not liking collision.
Your answer
Follow this Question
Related Questions
2d Platformer Jumping Not Working 1 Answer
Jump Not Working 1 Answer
GetButtonDown not always firing 1 Answer
my ball sometimes jumps higher or sometimes not 2 Answers
2D Player Movement C# 3 Answers