Hey there!
So I am adding some player-controls to my player in my game.
However, even though I got my doublejump working, I still find two flaws with it. (My aim is to make an super smash kind of game)
If you double tap the jump button you fly ridiculously further up than intended.
To fix this problem, I tried to put in a delay of 0.5-1 sec after the jump from the ground, but did not manage to make that work in my script. Also open for other solutions than delay.
When falling down and pressing the jump button, you will not jump much at all, but merely just stop the falling to start falling again.
I though I could add some more force on the second jump, but that feels like I am making things too clunky, so maybe there is some way to remove the gravity on the object for a split second, and executing the jump directly afterwards.
PlayerController Script (C#):
public class PlayerController : MonoBehaviour {
public float maxSpeed = 10f;
bool facingRight = true;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public float jumpForce = 700;
bool doubleJump = false;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void FixedUpdate () {
grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);
anim.SetBool ("Ground", grounded);
anim.SetFloat("vSpeed", GetComponent<Rigidbody2D>().velocity.y);
if (grounded) {
doubleJump = false;
}
float move = Input.GetAxis ("Horizontal");
anim.SetFloat ("Speed", Mathf.Abs (move));
GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (move > 0 && !facingRight){
Flip ();
}
else if (move < 0 && facingRight) {
Flip ();
}
}
void Update(){
if ((grounded || !doubleJump) && Input.GetKeyDown (KeyCode.W) || Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKeyDown (KeyCode.Space)) {
anim.SetBool("Ground", false);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, jumpForce));
if(!doubleJump && !grounded){
doubleJump = true;
}
}
}
void Flip () {
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}