obsidian/笔记文件/2.笔记/Unity2d检测方法 - Physics2D.OverlapCircle().md
2025-03-26 00:02:56 +08:00

1.0 KiB
Raw Permalink Blame History

#unity/日常积累

检查 Collider 是否落在圆形区域内。圆由其在世界空间中的中心坐标及其半径定义。可选的 layerMask 允许测试仅检查特定层上的对象。尽管 Z 轴与 2D 中的渲染或碰撞无关,但您以使用 minDepth 和 maxDepth 参数根据对象的 Z 坐标过滤对象。如果有多个 Collider 落在圆圈内,则返回的将是 Z 坐标值最低的那个。如果圆圈中没有 Collider则返回 Null。

public static Collider2D OverlapCircle(Vector2 point, float radius, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);

!Pasted image 20240219122039.png

使用样例:

    private void CheckSurroundings()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
    }

在编辑器内看到圆形区域的方法:

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
    }