- Home /
2D double jump doesn't work.
hey guys, i am trying to make a 2d endless runner game. this is my script for the player. I want my player to be able to double jump, but there is some chance when my player triple-jumps in the air. what's wrong with this?
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Animator))]
public class PlayerMovement : MonoBehaviour {
public float moveSpeed;
public float jumpForce;
private Rigidbody2D rb;
[SerializeField]
private int jumps;
public LayerMask ground;
private Animator anim;
[SerializeField]
private bool isGrounded = false;
void Start () {
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
void Update(){
isGrounded = rb.IsTouchingLayers(ground);
anim.SetBool("Grounded", isGrounded);
anim.SetFloat("Speed", 1f);
if (isGrounded) jumps = 0;
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene("Endless");
}
if (Input.GetButtonDown("Jump"))
{
if (jumps < 2)
{
rb.velocity = new Vector2(rb.velocity.x, 0);
rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
jumps++;
}
}
Debug.Log(jumps);
}
void FixedUpdate () {
rb.velocity = new Vector2(moveSpeed * Time.fixedDeltaTime, rb.velocity.y);
}
}
Answer by brunocoimbra · Jan 04, 2016 at 02:43 PM
Maybe the problem is here:
isGrounded = rb.IsTouchingLayers(ground);
Try moving it to the FixedUpdate(), as the Update() can be called before the physics has been updated. Also, after jumping, set isGrounded to false, so it will need to wait the physics's update to ensure that you can jump.
If that doesn't help, then try making this:
Create an empty object as a child from player, and put a small collider as a trigger in it (this collider must cover the "feet area"). Now add this:
[SerializeField]
private Collider2D feetCollider; // pass your "feet area" collider here.
and change this:
isGrounded = rb.IsTouchingLayers(ground);
for this:
isGrounded = feetCollider.IsTouchingLayers(ground);
Answer by RavenOfCode · Jan 04, 2016 at 01:24 PM
Personally I would just use a int for the amount of jumps and just use that, and check for the collision with the ground with OnCollisionEnter. With this you can set maxJumps to 2 for double, 3 for triple, ect.
int jumps;
int maxJumps; //set to 2 for double jump
void Start ()
{
jumps = maxJumps;
}
void Update ()
{
if (GetButtonDown ("Jump")) //gets tap
{
if (jumps > 0)
{
jumps--;
//do jump code
}
}
}
void OnCollisionEnter2D (Collision2D other)
{
if (other.tag == "Terrain") //hits terrain
{
jumps = maxJumps; //regenerates jump
}
}
Well, I did not use you answers code, but anyway, thanks for taking time to answer!