看教材(Learning C# Programming with Unity 3D, Second Edition)时的一个代码片段
Camera myCamera = Camera.main;
void Update()
{
/*
* Section 4.3.1 Mouse Point
*/
Ray ray = myCamera.ScreenPointToRay(Input.mousePosition, Camera.MonoOrStereoscopicEye.Mono); //Camera.MonoOrStereoscopicEye default:mono
Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 h = hit.point;
h.y = 0;
myTransformObject.transform.position = h;
}
/*
* The ray becomes a line that starts at the myCamera as a point that passes
* through the Input.mousePosition and continues through to the game world.
*
* If the ray hits something with a collider on it
* then Physics will tell us if that ray has collided with
* a solid object in the world.
*/
}
看书时遇到第一行一直无法理解这个射线是怎么回事(现在想想感觉是脑子抽了
在这边Input.mousePosition
是鼠标位置
看看官方文档:Camera.ScreenPointToRay - doc
public Ray ScreenPointToRay(Vector3 pos);
public Ray ScreenPointToRay(Vector3 pos, Camera.MonoOrStereoscopicEye eye);
- Returns a ray going from camera through a screen point.
- Resulting ray is in world space, starting on the near plane of the camera and going through position’s (x,y) pixel coordinates on the screen (position.z is ignored).
- Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth -1,pixelHeight -1).
返回相机穿过屏幕上的点的光线
听起来听拗口的, 其实就是以相机为原点,向目标物所在的方向发射出去的射线, 大概就是图下这种状态。(研究路径什么的善用DrawRay
RaycastHit
A structure used to get information back from a raycast.
但是在这块的话用的是下面这一重载
- 关键字
out
: You can use the out keyword in two contexts:- As a parameter modifier, which lets you pass an argument to a method by reference rather than by value.
- In generic type parameter declarations for interfaces and delegates, which specifies that a type parameter is covariant.