I'm making a basic 3D First Person project using the movement code below, but I can only jump at a certain angle.
How can I fix this so that my character can jump anywhere?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("References")]
public Rigidbody rb;
public Transform head;
public Camera camera;
[Header("Configurations")]
public float walkSpeed;
public float runSpeed;
public float jumpSpeed;
[Header("Runtime")]
Vector3 newVelocity;
bool isGrounded = false;
bool isJumping = false;
// Start is called before the first frame update
void Start() {
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void Update() {
transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * 2f);
newVelocity = Vector3.up * rb.velocity.y;
float speed = Input.GetKey(KeyCode.LeftShift) ? runSpeed : walkSpeed;
newVelocity.x = Input.GetAxis("Horizontal") * speed;
newVelocity.z = Input.GetAxis("Vertical") * speed;
if (isGrounded) {
if (Input.GetKeyDown(KeyCode.Space) && !isJumping) {
newVelocity.y = jumpSpeed;
isJumping = true;
}
}
}
void FixedUpdate() {
rb.velocity = transform.TransformDirection(newVelocity);
if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, 1f))
isGrounded = true;
else isGrounded = false;
}
void LateUpdate() {
Vector3 e = head.eulerAngles;
e.x -= Input.GetAxis("Mouse Y") * 2f;
e.x = RestrictAngle(e.x, -85, 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;
}
void OnCollisionStay(Collision col) {
isGrounded = true;
isJumping = false;
}
void OnCollisionExit(Collision col) {
isGrounded = false;
}
}
```
isGrounded
logic seems a bit off, since it should be possible to trigger multiple jumps before the player is 1f off the ground with how you set to to true/ false. Also for what reason are you using both the Collision methods and a raycast for ground detection? \$\endgroup\$