I am having a problem with my code, whenever I click the q key down some times unity responds and my player jumps but then other times my player doesn’t jump at all and the engine doesn’t respond. I’ve tryed everything but I can’t find a solution.
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header(“References”)]
public Rigidbody rb;
public Transform head;
public Camera playerCamera;
[Header("Configurations")]
public float walkSpeed;
public float runSpeed;
public float jumpSpeed;
public float groundCheckDistance = 1.1f; // Distance for ground check
[Header("Runtime")]
Vector3 newVelocity;
bool isGrounded = false;
bool isJumping = false;
void Start()
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * 2f);
newVelocity = rb.velocity;
float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
newVelocity.x = Input.GetAxis("Horizontal") * speed;
newVelocity.z = Input.GetAxis("Vertical") * speed;
// Handle Jumping Input
if (isGrounded && Input.GetKeyDown(KeyCode.Q) && !isJumping)
{
newVelocity.y = jumpSpeed;
isJumping = true;
}
}
void FixedUpdate()
{
// SphereCast for ground detection (radius a bit smaller than capsule's)
isGrounded = Physics.SphereCast(transform.position, 0.4f, Vector3.down, out RaycastHit hit, 1.1f);
// Apply movement
rb.velocity = transform.TransformDirection(newVelocity);
// Reset jump if grounded
if (isGrounded)
{
isJumping = false;
}
}
void LateUpdate()
{
Vector3 e = head.eulerAngles;
e.x -= Input.GetAxis("Mouse Y") * 2f;
e.x = RestrictAngle(e.x, -85f, 85f);
head.eulerAngles = e;
}
public static float RestrictAngle(float angle, float angleMin, float angleMax)
{
if (angle > 180)
angle -= 360;
else if (angle < -180)
angle += 360;
if (angle > angleMax)
angle = angleMax;
if (angle < angleMin)
angle = angleMin;
return angle;
}
}