C#, Unity

C#, Unity) 범위 안 Enemy 판별

나무늘보섬 2024. 7. 13. 21:28

- 우선 Gizmo로 플레이어의 범위를 가시적으로 설정하기

(Gizmo: any small device with a particular purpose)

더보기

private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawCube(this.transform.position + boxCenterOffset, new Vector2(boxSize.x, boxSize.y));
    }

 

// 색깔은 상관 X, new Color ( -, -, -, -) 로 색깔 조정 가능, alpha값도 투명하게 가능

// 현재 2D게임이므로 Vector2

 

※ 추가 Gizmos 관련 함수 - OnDrawGizmosSelected()

- 선택된 오브젝트만 Gizmo를 보여줌 


 

- Enemy는 Polygon Collider 2D로 설정되어 있음.

- Overlap관련 함수는 많이 존재해서 경우에 따라 필요한 걸 찾아 쓰는 것이 최선일 듯 (ex: Overlap , OverlapSphere)

더보기

 Collider2D[] enemyArray = Physics2D.OverlapBoxAll((Vector2)(this.transform.position) + (Vector2)boxCenterOffset, boxSize, 0f);

 

// OverlapBoxAll은 많은 충돌체를 동시 감지 

 


 

- Linq (데이터 쿼리 기능 -> 처음 써봄) 를 사용해서 해당하는 데이터 조건을 배열에 삽입하기 

더보기

// 'enemy' 태그를 가진 PolygonCollider2D만 필터링

private Collider2D[] detectedEnemies; 
        detectedEnemies = enemyArray

            .Where(collider => collider.CompareTag("Enemy") && collider is PolygonCollider2D)

            .OrderBy(collider => Vector2.Distance(this.transform.position, collider.transform.position))   
            .ToArray();

 

// 담았던 모든 Collider들을 다음 조건에 맞게 detectedEnemies에 넣는 과정 -> enemy 판별하기

 

 // => 람다

 // Where: 조건을 만족하는 요소 필터링

 // OrderBy: 오름차순 정렬

 // ToArray: 배열로 변환

 

- 데이터 쿼리(Linq)기능은 처음 써 봤는데 데이터 처리 관련 부분에서 앞으로 유용하게 사용할 것 같다.

- 람다식 (lambda expression)도 거의 안 쓰는데 이런 기회일 때 써봐서 까먹지는 말자.

 

 

 

 

참고

- https://dictionary.cambridge.org/ko/%EC%82%AC%EC%A0%84/%EC%98%81%EC%96%B4/gizmo

 

gizmo

1. any small device with a particular purpose: 2. any small device with a…

dictionary.cambridge.org

 

- https://hsh12345.tistory.com/270

 

Unity) [유니티 2D] Physics2D를 활용한 스킬 범위공격 구현

using System.Collections; using System.Collections.Generic; using UnityEngine; public class SubmachineGunSkill_03 : Skill { protected override void Start() { this.isCircle = true; this.existTime = 0.783f; if (GameObject.Find("PlayerShell").transform.positi

hsh12345.tistory.com

- https://chatgpt.com/