Hi, i’m fairly new to unity and C# programming overall and i am trying to make a basic physics based movement script but the problem i have now is that i’m trying to make my player jump by checking if he’s grounded with a raycast. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
private bool grounded;
public float jumpforce;
private float distToGround;
public float thrust;
public Rigidbody rb;
public Transform PlayerCam;
public Collider PlayerCollider;
public float sensitivity;
private float xRotation;
private float desiredX;
void Start(){
rb = GetComponent<Rigidbody>();
distToGround = PlayerCollider.bounds.extents.y;
}
void Update(){
movement();
rotation();
jump();
GroundCheck();
}
void movement(){
if (Input.GetKey("z") && grounded == true)
{
rb.AddRelativeForce(Vector3.forward * thrust * Time.deltaTime);
print("z");
}
if (Input.GetKey("s") && grounded == true)
{
rb.AddRelativeForce(Vector3.back * thrust * Time.deltaTime);
print("s");
}
if (Input.GetKey("q") && grounded == true)
{
rb.AddRelativeForce(Vector3.left * thrust * Time.deltaTime);
print("q");
}
if (Input.GetKey("d") && grounded == true)
{
rb.AddRelativeForce(Vector3.right * thrust * Time.deltaTime);
print("d");
}
}
void rotation(){
float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime;
Vector3 rot = transform.localRotation.eulerAngles;
desiredX = rot.y + mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
PlayerCam.transform.rotation = Quaternion.Euler(xRotation, desiredX, 0 );
transform.localRotation = Quaternion.Euler(0, desiredX, 0);
}
void GroundCheck(){
if (Physics.Raycast(transform.position, Vector3.down, distToGround + 0.1f)) {
grounded = true;
print("grounded");
} else {grounded = false; print("not grounded");}
}
void jump(){
if (Input.GetKeyDown("space") && grounded == true){
rb.AddForce(Vector3.up * jumpforce * Time.fixedDeltaTime);
}
}
}
But the problem i’m having currently is that when the player (currently a capsule) is standing on a ledge, the raycast won’t detect that it’s grounded because the collider isn’t only in the middle. Maybe i should add more raycasts but i tought it was a good idea to ask for suggestions here. (If you have any other suggestions for my code it would also be appreciated).
this is a sreenshot of the problem:

Hi, thanks for responding to my question. Indeed, i saw it was also possible to do it like that but on an older question i saw someone saying that the OnCollisionExit method wasn't reliable and it's better to use raycasts instead. Is this still true or has this since been fixed ? Either way thanks for the response and i'll see if it works later today or next week.
– albadalejoluca