射线检测

1、摄像机发出射线,碰撞到plane。
这里写图片描述
代码:

void Start () 
    {
        UIEventListener.Get(this.gameObject).onPress = Press;
    }

    public void Press (GameObject go, bool pressed)
    {
        if(pressed)
        {
            RaycastHit hit;
            if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit))
            {
                Debug.LogError(hit.transform.tag);
                Debug.LogError(hit.distance);
            }
        }
    }

2、任意物体发射一条射线:
这里写图片描述

代码:

  public Transform btn;
    void Start () 
    {
        UIEventListener.Get(btn.gameObject).onPress = Press;
    }

    public void Press (GameObject go, bool pressed)
    {
        if(pressed)
        {
            RaycastHit hit;
            if (Physics.Raycast(this.transform.position, this.transform.forward, out hit))
            {
                Debug.LogError(hit.transform.tag);
                Debug.LogError(hit.distance);
            }
        }
    }

3、平面和射线的交点,以及点到平面的距离(有符号的距离),因为平面有法线,点在平面的前面还是后面。
这里写图片描述

代码:

public Transform btn;
    void Start () 
    {
        UIEventListener.Get(btn.gameObject).onPress = Press;
    }

    public void Press (GameObject go, bool pressed)
    {
        if(pressed)
        {
            //射线到平面的交点
            Plane plane = new Plane(Vector3.forward, Vector3.zero);
            Ray ray = new Ray(new Vector3(0, 0, 1), new Vector3(1, 0, -1));
            float distance = 0;
            if (plane.Raycast(ray, out distance))
            {
                Debug.LogError(distance);
            }

            //点到平面的距离
            distance = plane.GetDistanceToPoint(new Vector3(0, 0, -1));
            Debug.LogError(distance);
        }
    }

3、从摄像机发出一条到屏幕上的点的射线
这里有两个点,一个是摄像机所在的位置,另外一个是鼠标点击屏幕的位置,两个点确定了一条射线。

public void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Debug.LogError(Input.mousePosition);
            Ray ray = UICamera.currentCamera.ScreenPointToRay(Input.mousePosition);
            Debug.LogError(ray.origin);
            Debug.LogError(ray.direction);
            Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值