I can’t figure out how to detect if a raycast shooting down is touching object. Physical ground check.
There are several ways to code up a Raycast. A simple version is this:
using UnityEngine;
public class Grounded : MonoBehaviour
{
bool grounded;
void Update()
{
grounded = Physics.Raycast(transform.position, Vector3.down, 0.51f);
print(grounded);
}
}
The trick is that a Raycast returns a Boolean so you can test that to see if it’s hit something. Also, make sure your distance is correct. In this example, I assumed a cube of (1, 1, 1) with its centre being at height 0.5f. In that case, I always specify the max distance for the raycast to be slightly more than half the cube height, hence 0.51f.
You can use the name of the game object or search a component on the game object.
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
RaycastHit hit;
void Update()
{
if (Physics.Raycast(transform.position,transform.forward,out hit,1000f))
{
if (hit.transform.name == "name of yout game object")
{
//do something
}
if (hit.transform.GetComponent<Rigidbody>() != null)
{
//do something else
}
}
}
}
If you hav eany questions please feel free to ask. I will try to reply when I see it.
Hope this helps