Hi there! I am writing a grounded check using Unity, and it is always returning false for whether it is grounded.
Why is this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gravity : MonoBehaviour
{
public bool isGrounded;
[SerializeField]
private float gravitySpeed;
[SerializeField]
private float gravityForce;
[SerializeField]
private float height = 2;
[SerializeField]
private float maxDist = 1;
private Vector3 offsetHeight;
private Vector3 spherePos;
void Start()
{
CharacterController charCont = GetComponent<CharacterController>(); //Get the character controller component from the player object
offsetHeight = new Vector3(0.0f, height/2, 0.0f);
}
// Update is called once per frame
void Update()
{
checkIfGrounded();
}
private void checkIfGrounded()
{
RaycastHit hit; //get a hit variable to store the hit information
spherePos = (transform.position - offsetHeight);
if (Physics.SphereCast(spherePos, 1, -transform.up, out hit, maxDist))
{
isGrounded = true;
} else {
isGrounded = false;
}
Debug.Log(isGrounded);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gravity : MonoBehaviour
{
public bool isGrounded;
[SerializeField]
private float gravitySpeed;
[SerializeField]
private float gravityForce;
[SerializeField]
private float height = 2;
[SerializeField]
private float maxDist = 1sf;
private Vector3 offsetHeight;
private Vector3 spherePos;
void Start()
{
CharacterController charCont = GetComponent<CharacterController>(); //Get the character controller component from the player object
offsetHeight = new Vector3(0.0f, .1f + height/2, 0.0f);
}
// Update is called once per frame
void Update()
{
checkIfGrounded(); //
}
void checkIfGrounded()
{
RaycastHit hit; //get a hit variable to store the hit information
spherePos = (transform.position - offsetHeight);
if (Physics.SphereCast(spherePos, .5f, Vector3.down, out hit, maxDist))
{
isGrounded = true;
} else {
isGrounded = false;
}
Debug.Log(isGrounded);
}
void OnDrawGizmosSelected()
{
// Draw a yellow sphere at the transform's position
Gizmos.color = Color.yellow;
Gizmos.DrawSphere(spherePos, .5f);
}
}
This is my code. The cast seems to be a meter or two below what it should, so when I raise it above the plane about a meter high it says it’s grounded, but above and below that it is false. How do I fix it?
From my experience, SphereCast will not return true in situation where the sphere already intersects the collider at the origin point. You might want to use OverlapSphere instead: