1.射线Ray
Ray from the camera
The
Ray
always corresponds to a point in the view, so the Camera class provides the
ScreenPointToRay
and
ViewportPointToRay
functions.
The
difference between the two
is that ScreenPointToRay expects the point to be provided as a pixel
coordinate, while ViewportPointToRay takes normalized coordinates in the range 0..1 (where 0 represents the bottom or left and 1
represents the top or right of the view).
Each of these functions returns a Ray which consists of a point of origin and a vector
which shows the direction of the line from that origin.
The Ray originates from the near clipping plane rather than the Camera’s
transform.position point.
2.Physics.Raycast
static bool
Raycast
(
Ray
ray
,
RaycastHit
hitInfo
, float
distance
= Mathf.Infinity, int
layerMask
= DefaultRaycastLayers);
ray | The starting point and direction of the ray. |
distance | The length of the ray. |
hitInfo | If true is returned, hitInfo will contain more information about where the collider was hit (See Also:RaycastHit). |
layerMask | A Layer mask that is used to selectively ignore colliders when casting a ray. |
Returns
bool True when the ray intersects any collider, otherwise false.
Description
Same as above using /ray.origin/ and /ray.direction/ instead of origin and direction.
using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, 100)) Debug.DrawLine(ray.origin, hit.point); } }
Cast a ray against all colliders except those in the
Player layer.
void
Update () {
// 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"
);
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection (Vector3.forward) *
1000
, Color.white);
Debug.Log(
"Did not Hit"
);
}
}
void
Update
()
{
Camera cam;
cam = UICamera.currentCamera;
Ray
ray
=
cam
.
ScreenPointToRay
(
Input
.
mousePosition
);
RaycastHit
hit
;
if ( Physics.Raycast(ray, out hit, 100,
gameObject
.layer ) )
{
Debug
.
Log
(
"Mouse over object"
);
}
}