unity3d 2d 射线检测

Physics2D.LinecastNonAlloc 直线投射不分配内存
C# ⇒ static int LinecastNonAlloc(Vector2 start, Vector2 end, RaycastHit2D[] results, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);

start:直线在世界空间的开始点。
end :直线在时间空间的结束点。
results:返回与直线相交的物体数组。 返回结果的数量(int)。
layerMask:只在某些层过滤检测碰撞器。
minDepth:只包括Z坐标(深度)大于这个值的对象。
maxDepth:只包括Z坐标(深度)小于这个值的对象。

具体 实例`using UnityEngine;
using System.Collections;

public class test : MonoBehaviour {

    public Transform targetpos;//目标位置//
    RaycastHit2D [] ray;
    int hitNumber =0;//检测返回与直线相交的物体数量//
    // Use this for initialization
    void Start () 
    {
        ray=new RaycastHit2D[5] ;
    }
    void FixedUpdate()
    {
        HitTest ();
    }
     void  HitTest()
    {
        hitNumber = Physics2D.LinecastNonAlloc (gameObject.transform .position,targetpos.transform.position ,ray,1<"GameModel"));
        for (int i = 0; i < hitNumber; i++) {
            Debug.DrawLine(gameObject.transform .position ,ray[i].transform.position,Color.red);
            print ("ray{"+i+"}.name"+ray[i].transform.name);
        }
    }
}

1< //在哪个层显示,mask 只在”GameModel”层显示。

unity3d 2d 射线检测_第1张图片

你可能感兴趣的:(unity-2d)