Pretty darn new to unity and using C#. I’ve been trying to modify the CharacterController2d to include a double-jump feature.
At first, you could jump infinitely so it felt like Badlands or Flappy Bird. I fixed that by including checks for bools CanDoubleJump and DoubleJumped, which dictate that if you have not yet jumped a second time, you may, but if you have jumped a second time, you may not.
This works. The problem that remains however, is after the first time I make the player jump (I can jump twice separately), every other time I jump, it seems to jump twice instantly.
In an attempt to create a necessary amount of time that must pass between jumps, I have made the DoJumpDelay function which uses float JumpDelay. I can’t figure out how to make this work. Can anyone help?
using UnityEngine;
using System.Collections;
public class CharacterController2d : MonoBehaviour
{
// settings
public float jumpforce = 500f;
public float latteralspeed = 5f;
// state
bool airborne = false;
bool CanDoubleJump = false;
bool DoubleJumped = false;
public float JumpDelay = 0.0f;// jumpdelay
private void DoJumpDelay ()
{
if (airborne && !DoubleJumped && JumpDelay > 0) {
JumpDelay -= Time.deltaTime;
}
if (JumpDelay < 0) {
JumpDelay = 0;
}
}
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey (KeyCode.A)) {
rigidbody2D.velocity = new Vector2 (-latteralspeed, rigidbody2D.velocity.y);
}
if (Input.GetKey (KeyCode.D)) {
rigidbody2D.velocity = new Vector2 (latteralspeed, rigidbody2D.velocity.y);
}
if (!airborne)
{
DoubleJumped = false;
if (Input.GetKeyDown (KeyCode.W))
{
rigidbody2D.AddForce (new Vector2 (0, jumpforce));
airborne = true;
JumpDelay = 10f; //jumpdelay
}
}
if (airborne && Input.GetKeyUp (KeyCode.W)) {
DoJumpDelay ();//
CanDoubleJump = true;
}
if (airborne && CanDoubleJump && !DoubleJumped && Input.GetKeyDown (KeyCode.W)) {
rigidbody2D.AddForce (new Vector2 (0, jumpforce));
CanDoubleJump = false;
DoubleJumped = true;
}
}
void OnCollisionEnter2D(Collision2D collision)
{
foreach (ContactPoint2D p in collision.contacts)
{
if (p.normal.y > 0.5f)
{
airborne = false;
}
}
}
}