天天看点

unity 2D射线的使用方法

Ray2D ray;

    void Update()

    {

        ray = new Ray2D(transform.position, Vector2.right);

        RaycastHit2D info = Physics2D.Raycast(ray.origin, ray.direction,10);

        //Debug.DrawRay(ray.origin,ray.direction,Color.blue);

        if (info.collider != null)

        {

            if (info.transform.gameObject.CompareTag("Boss"))

            {

                Debug.LogWarning("检测到敌人");

            }

            else

            {

                Debug.Log("检测到其他对象");

            }

        }

        else

        {

            Debug.Log("没有碰撞任何对象");

        }

    }

https://blog.csdn.net/yjy99yjy999/article/details/82904207

//起点、方向

RaycastHit2D info = Physics2D.Raycast(startPos, Vector2.right); //无限远

//起点、方向、距离:

RaycastHit2D info = Physics2D.Raycast( startPos, direction, 10f );

//如果已经定义了光线,可以使用光线的信息投射:

RaycastHit2D info = Physics2D.Raycast(ray.origin, ray.direction);

只对指定层级激活

正确用法1

//使用Layer ID 

 RaycastHit2D info = Physics2D.Raycast(transform.position, dir, dist, 1<<14);

正确用法2:

//使用Layer Name

int LayerID = LayerMask.NameToLayer("Enemy");

RaycastHit2D info = Physics2D.Raycast(transform.position, dir, dist, 1<<LayerID);

用法说明:这个参数是一个奇妙的int值,用一个数字表示了所有图层包含与否的设置。

1 <<  14 表示仅包含14层(不包含其余的层)

~(1<<14) 表示不包含14层(包含其他所有层)

(1<<12) | (1<<14) 表示包含12、14层 (不包含其余层)