title | category | layout | tags | prism_languages | ||
---|---|---|---|---|---|---|
Raycast |
Physics |
2017/sheet |
|
|
float distance = 0.5f;
if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, distance)) {
Debug.log("Hit some obstacle!");
}
RaycastHit hit;
// Unlike this example, most of the time you should pass a layerMask as the last option to hit only to the ground
if (Physics.Raycast(transform.position, -Vector3.up, out hit, distance)) {
Debug.log("Hit something below!");
}
void FixedUpdate() {
// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask)) {
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
}