- Home /
BoxCast to tell if player is grounded
I'm trying to figure out how to use BoxCast to tell if a player is grounded. Previously I was using RayCast but now I want to use BoxCast so it's more accurate (the player is a Cube). I can't get isGrounded() to return true when the player is on the ground with BoxCast
using System.Collections;
using UnityEngine;
public class movement : MonoBehaviour {
private Rigidbody rb;
public float speed = 5;
public float jumpSpeed = 500;
public int playerNumber = 1;
public GameObject jumpChecker;
private bool grounded = false;
void Start () {
rb = GetComponent<Rigidbody> ();
}
public float isGroundedRayLength = 0.1f;
public LayerMask layerMaskForGrounded;
public void isGrounded () {
Vector3 position = transform.position;
//position.y = GetComponent<Collider>().bounds.min.y + 0.1f;
// float length = isGroundedRayLength + 0.1f;
// Debug.DrawRay (position, Vector3.down * length);
// grounded = Physics.Raycast (position, Vector3.down, length, layerMaskForGrounded.value);
grounded = Physics.BoxCast(
position,
new Vector3(0.5f, 0.5f, 0.5f),
Vector3.down,
transform.rotation,
isGroundedRayLength,
layerMaskForGrounded.value);
}
void FixedUpdate () {
var moveDirection = new Vector3 (Input.GetAxisRaw ("Horizontal" + playerNumber), 0, Input.GetAxisRaw ("Vertical" + playerNumber));
rb.MovePosition (rb.position + moveDirection * speed * Time.deltaTime);
bool jump = Input.GetButtonDown ("Jump" + playerNumber);
if (jump && grounded)
{
grounded = false;
rb.AddForce (0, jumpSpeed, 0);
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Clear gaps/cuts in trail renderer 0 Answers
Help with rotation. 1 Answer
"on" and "off" the effect. 0 Answers
MY variables RESET When calling Destroy() In Unity 1 Answer
How do i Achieve mesh Extrusion? 2 Answers