前言
最近在寫敵人的行動邏輯,其中涉及到“判定玩家是否在攻擊范圍內”的問題,現在學習這兩種方法,以期解決該問題。
API對Physics2D.CircleCast的(部分)說明
public static RaycastHit2D CircleCast(Vector2 origin, float radius, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity
A CircleCast is conceptually like dragging a circle through the Scene in a particular direction. Any object making contact with the circle can be detected and reported.
從概念上說,CircleCast 就像朝特定方向拖動一個圓形穿過場景一樣。在該過程中,可以檢測並報告與圓形接觸的任何對象。
最重要的概念是“CircleCast 就像朝特定方向拖動一個圓形穿過場景一樣”,而這個圓的半徑由我們傳入的radius來確定。其它的細節則與RayCast幾乎無異。
API對Physics2D.OverlapCircle的(部分)說明
public static Collider2D OverlapCircle(Vector2 point, float radius, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);
返回值
Collider2D The Collider overlapping the circle.
Collider2D 與該圓形重疊的碰撞體。
描述
The circle is defined by its centre coordinate in world space and by its radius.
圓形由其在世界空間中的中心坐標及其半徑定義。
The optional layerMask allows the test to check only for objects on specific layers.
可選的 layerMask 可讓測試僅檢查特定層上的對象。
Although the Z axis is not relevant for rendering or collisions in 2D, you can use the minDepth and maxDepth parameters to filter objects based on their Z coordinate.
雖然 Z 軸與 2D 中的渲染或碰撞無關,但您可以使用 minDepth 和 maxDepth 參數根據其 Z 軸坐標篩選對象。
If more than one Collider falls within the circle then the one returned will be the one with the lowest Z coordinate value.
如果有多個碰撞體位於該圓形內,則返回 Z 坐標值最小的碰撞體。
Null is returned if there are no Colliders in the circle.
如果該圓形內沒有任何碰撞體,則返回 Null。
總結
Physics2D.CircleCast | Physics2D.OverlapCircle | |
---|---|---|
返回值 | RaycastHit2D | Collider2D |
投射方式 | 就像朝特定方向拖動一個圓形穿過場景 | 在世界空間中投射圓形 |
檢測條件 | 與圓形接觸的第一個碰撞體 | 在該圓形區域內的,z坐標最小的碰撞體 |
若未檢測到 | RaycastHit2D.collider = null | Collider2D = null |
補充
在API中,還能查閱到一些“和這兩個方法分別相似”的方法,比如:
BoxCast、CapsuleCast、CircleCastAll;OverlapBox、OverlapCapsule、OverlapCircleAll等。它們和這兩個方法有很多相同的地方,也有一些差異,具體如何去查閱API,不再一一介紹。
參考資料
Unity API CircleCast(EN)
Unity API CircleCast(CN)
Unity API OverlapCircle(EN)
Unity API OverlapCircle(CN)