[Unity3D] Camera.ScreenPointToRay RaycastHit Physics.Raycast

看教材(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.
在这里插入图片描述

Physics.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.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值