카테고리 없음

2D 클리커 게임 팀 프로젝트 중

rxo2 2025. 3. 27. 20:53

클릭커 게임의 클릭시 이벤트효과 구현중

클릭에 필요한 정보는 클릭의 위치값과 화면 좌표값을 월드 좌표로 변환 하는것이 기본으로 보인다

 

public class ClickAttack : MonoBehaviour
{
    [SerializeField] float click_Damage = 1.0f;
    private Camera mainCamera;

    private void Awake()
    {
        mainCamera = Camera.main; // 현재씬의 카메라 가져오기
        _clickAtt = new InputAction(); // 인풋액션 인스턴스 생성
    }

    public void OnClickAttack(InputAction.CallbackContext context)
    {
        if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject())
        { 
         // UI요소 위에서 클릭되었는지 확인하는 함수,EventSystem.current 가 존재하면 UI 클릭 감지 가능
            Debug.Log("ui 클릭 공격 실행 안됨");
            return;
        }
        Vector2 mousePosition = Mouse.current.position.ReadValue(); // 클릭위치값 가져오기
        Vector2 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition); // 화면 좌표를 월드좌표로 변환
        RaycastHit2D hit = Physics2D.Raycast(worldPosition, Vector2.zero);
        // 2D에서 더 정확한 Raycast 작동 (Physics2D.Raycast는 방향이 필요 없다)

        if (hit.collider != null )
        {
            Monster monster = hit.collider.GetComponent<Monster>();

            if (monster != null)
            {
                Attack(click_Damage);
            }
        }
}

위의 코드에서 내가 생각한 주요 포인트는 아래와 같다

 

EventSystem.current != null && EventSystem.current.IsPointerOverGameObject()
// UI요소 위에서 클릭되었는지 확인하는 함수,EventSystem.current 가 존재하면 UI 클릭 감지 가능

 

Vector2 mousePosition = Mouse.current.position.ReadValue(); // 클릭위치값 가져오기

 

Vector2 worldPosition = mainCamera.ScreenToWorldPoint(mousePosition); // 화면 좌표를 월드좌표로 변환

 

RaycastHit2D hit = Physics2D.Raycast(worldPosition, Vector2.zero);
//2D에서 더 정확한 Raycast 작동 (Physics2D.Raycast는 방향이 필요 없다)