I'm trying to make double jumps for my FPS game in Unity. I have written so that if I press "Jump", (the space bar) and that I'm not grounded, I will jump again and that I wont be able to double jump any more by turning off a public bool. Normally if I'm falling and I press jump, I will jump and it works, but when I jump the first time, the canDoublejump
bool just turns off, so could you someone maybe help me with it?
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//Character Controller new name
public CharacterController controller;
//Basic Starting values
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 2.5f;
public float doublejumpMultiplier = 0.5f;
public bool canDoublejump = true;
public bool grounded = true;
//Assingables
public Transform playerCam;
//Other
private void Jump()
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
//New names for stuff and assignables
private Rigidbody rb;
//Not falling forever lol
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
//Random Bullshit
if (isGrounded) grounded = true;
if (!isGrounded) grounded = false;
//Gravity stuff
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
//Walking
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
//Jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
Jump();
canDoublejump = true;
}
//Running
if (Input.GetButton("LeftShift")) speed = 12f;
if (Input.GetButtonUp("LeftShift")) speed = 6f;
if (Input.GetButton("LeftShift")) jumpHeight = 4.25f;
if (Input.GetButtonUp("LeftShift")) jumpHeight = 2.5f;
//Crouching
if (Input.GetButton("LeftCtrl")) controller.height = 1.2f;
if (Input.GetButtonUp("LeftCtrl")) controller.height = 2f;
if (Input.GetButton("LeftCtrl")) speed = 3f;
if (Input.GetButtonUp("LeftCtrl")) speed = 6f;
//Crawling
if (Input.GetButton("C")) controller.height = 0.25f;
if (Input.GetButtonUp("C")) controller.height = 2f;
if (Input.GetButton("C")) speed = 1.75f;
if (Input.GetButtonUp("C")) speed = 6f;
//DoubleJump
if (isGrounded) canDoublejump = true;
if (!isGrounded && canDoublejump == true)
{
if(Input.GetButton("Jump"))
{
Jump();
}
}
if (!isGrounded && Input.GetButton("Jump"))
{
canDoublejump = false;
}
}
}