Ray
struct
Properties | Description |
---|
direction | The direction of the ray. | origin | The origin point of the ray. |
Constructors | Description |
---|
Ray | Creates a ray starting at origin along direction. |
Public Methods | Description |
---|
GetPoint | Returns a point at distance units along the ray. | ToString | Returns a nicely formatted string for this ray. |
RaycastHit
struct
Properties | Description |
---|
barycentricCoordinate | The barycentric coordinate of the triangle we hit. | collider | The Collider that was hit. | distance | The distance from the ray’s origin to the impact point. | lightmapCoord | The uv lightmap coordinate at the impact point. | normal | The normal of the surface the ray hit. | point | The impact point in world space where the ray hit the collider. | rigidbody | The Rigidbody of the collider that was hit. If the collider is not attached to a rigidbody then it is null. | textureCoord | The uv texture coordinate at the collision location. | textureCoord2 | The secondary uv texture coordinate at the impact point. | transform | 射线撞到的collider或者rigidbody所属物体的transform | triangleIndex | The index of the triangle that was hit. |
Camera类中提供的用法
- Ray 始终对应于视图中的一个点,因此 Camera 类提供 ScreenPointToRay 和 ViewportPointToRay函数。两者之间的区别在于 ScreenPointToRay 期望以像素坐标的形式提供该点,而 ViewportPointToRay 则接受0…1 范围内的标准化坐标(其中 0 表示视图的左下角,1 表示右上角)。这些函数中的每一个函数都返回由一个原点和一个矢量(该矢量显示从该原点出发的线条方向)组成的 Ray。
- Ray源自近裁剪面而不是摄像机 (Camera) 的 transform.position 点。
1、通过鼠标位置点击场景中的物体,“这是一种基于对象在屏幕上的图像来定位对象的非常有用的方法。”
public class ExampleScript : MonoBehaviour {
public Camera camera;
void Start(){
RaycastHit hit;
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)) {
Transform objectHit = hit.transform;
}
}
}
2、沿着射线移动相机
public class ExampleScript : MonoBehaviour {
public bool zooming;
public float zoomSpeed;
public Camera camera;
void Update() {
if (zooming) {
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
float zoomDistance = zoomSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
camera.transform.Translate(ray.direction * zoomDistance, Space.World);
}
}
}
|