Im making a 3-D game and i want to do ground check. Since the object is 3-D, instead of using a rayCast im using a BoxCast. I created an empty game object that stores the orign of boxcast. I created a boxCast from that gameObject downwards (-transform.up OR Vector3.down).
I used a gizmo as well to keep a track of the box.
There is a small probelm tho. As soon as the box touches the ground, the player is slowing down and after reaching the ground, onGround is getting disabled and movement is getting disabled. What am i doing wrong?
using UnityEngine;
public class PlayerMovementScript : MonoBehaviour
{
[SerializeField] float speed;
[SerializeField] float groundDist;
[SerializeField] bool onGround;
[SerializeField] LayerMask terrainLayer;
[SerializeField] Rigidbody rb;
[SerializeField] Vector3 boxSize;
[SerializeField] Transform boxcastOrign;
private void Start()
{
rb = gameObject.GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
// onGround = Physics.Raycast(transform.position, Vector3.down, groundDist, terrainLayer);
onGround = Physics.BoxCast(boxcastOrign.position, boxSize / 2, -transform.up, Quaternion.identity, boxSize.y, terrainLayer);
if (onGround)
{
Debug.Log(onGround);
}
if (onGround)
{
float xValue = Input.GetAxis("Horizontal");
float yValue = Input.GetAxis("Vertical");
Vector3 moveDirection = new Vector3(xValue, 0, yValue);
rb.velocity = moveDirection * speed;
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
// Gizmos.DrawLine(transform.position, transform.position + Vector3.down * groundDist);
Gizmos.DrawWireCube(boxcastOrign.position, boxSize);
}
}