I’m trying to draw a simple RayCast to see if I’m on the ground or not:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeTest : MonoBehaviour {
public float mouseSensitivity = 15.0f;
public float moveSpeed = 15.0f;
//this handles the camera rotation
private float camRot;
private float distToGround;
// Use this for initialization
void Start () {
//initialize the camRot to the starting rotation
camRot = 30.0f;
//initialize the camera child rotation
transform.Find("Main Camera").localRotation = Quaternion.Euler(30.0f, 0, 0);
//Gets the distance to the bottom of the capsule collider
distToGround = GetComponent<Collider>().bounds.extents.y;
}
// Update is called once per frame
void Update () {
MoveMe();
}
void MoveMe()
{
//get the X axis rotation used for the game object rotation
var xRot = Input.GetAxis("Mouse X") * Time.deltaTime * 20.0f * mouseSensitivity;
//get the rotation used for the camera child rotation
camRot += Input.GetAxis("Mouse Y") * Time.deltaTime * 10.0f * mouseSensitivity;
//get the X and Z axis movement used for the game object movement
var xTran = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
var zTran = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
//clamp the rotation for the camera
camRot = Mathf.Clamp(camRot, -30f, -7.5f);
//set the rotation for the camera
transform.Find("Main Camera").localRotation = Quaternion.Euler(-camRot, 0, 0);
//rotate the game object
transform.Rotate(0, xRot, 0);
//move the game object
transform.Translate(xTran, 0, zTran);
if (Input.GetKeyDown("space") && IsGrounded())
{
gameObject.GetComponent<Rigidbody>().AddForce(transform.up * 10f, ForceMode.Impulse);
}
}
bool IsGrounded()
{
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.3f);
}
}
No matter what I do, I can still jump in midair infinitely. Why is the check not working?