Unity 十四 射线二

Unity 里有两种射线,

  1. 一个不可以穿透物体的射线Physics.Raycast,如下图,射线被胶囊体挡住。
    在这里插入图片描述
  2. 一个可以穿透物体的射线Physics.RaycastAll,该方法可以检测所有射线碰撞的物体
    在这里插入图片描述

两种方法分别写了一个例子。

Physics.Raycast

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayTest : MonoBehaviour
{
    // Start is called before the first frame update
    private RaycastHit raytest;
    private Ray a;
    void Start()
    {
       
     
    }

    private void Update()
    
    {
        a = new Ray(transform.position,transform.forward);
        int b = LayerMask.GetMask("test","test1");
        int c = (1 << 9) | (1 << 10);
        
        Debug.Log("b::::::::"+b+",,,,,c::::::"+c);
        
        if(Physics.Raycast(a,out raytest,200,b)){
            Debug.Log(raytest.point);
            Debug.Log(raytest.transform.name);
        }
        Debug.DrawLine(transform.position,raytest.point,Color.magenta);
    }
}
 

Physics.RaycastAll

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayTestAll : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Ray ray = new Ray(transform.position,transform.forward);
       RaycastHit[] rays = Physics.RaycastAll(ray, 100);
        foreach (var VARIABLE in rays)
        {
            Debug.Log(VARIABLE.transform.name);
        }
        Debug.DrawLine(transform.position,transform.forward*100,Color.red);
    }
}

发布了56 篇原创文章 · 获赞 24 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u014196765/article/details/93502002