I’m working on a Unity 3D project and my double jump boolean does not properly reset. It works as intended if the character becomes airborne while either running or walking, but the “doubleJump” boolean will turn into false if I begin a jump while standing still. Can anyone help me identify the problem?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
public Camera playerCamera;
public float walkSpeed = 6f;
public float runSpeed = 12f;
public float jumpPower = 7f;
public float gravity = 10f;
public float lookSpeed = 2f;
public float lookXLimit = 45f;
public float defaultHeight = 2f;
public float crouchHeight = 1f;
public float crouchSpeed = 3f;
public bool doubleJump = true;
private Vector3 moveDirection = Vector3.zero;
private float rotationX = 0;
private CharacterController characterController;
private bool canMove = true;
void Start()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
moveDirection.x = forward.x * curSpeedX + right.x * curSpeedY;
moveDirection.z = forward.z * curSpeedX + right.z * curSpeedY;
if (Input.GetKeyDown(KeyCode.LeftControl) && !characterController.isGrounded)
{
moveDirection.y = -100;
}
if (characterController.isGrounded) //INTENTA USAR "JUMPS REMAINING" EN LUGAR DE ESTO
{
doubleJump = true;
moveDirection.y = -0.1f;
if (Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpPower;
doubleJump = true;
}
}
else
{
if (Input.GetButtonDown("Jump") && doubleJump)
{
moveDirection.y = jumpPower;
doubleJump = false;
}
moveDirection.y -= gravity * Time.deltaTime;
}
if (Input.GetKey(KeyCode.R) && canMove)
{
characterController.height = crouchHeight;
walkSpeed = crouchSpeed;
runSpeed = crouchSpeed;
}
else
{
characterController.height = defaultHeight;
walkSpeed = 6f;
runSpeed = 12f;
}
characterController.Move(moveDirection * Time.deltaTime);
if (canMove)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
}
}