버튼을 마우스로 클릭한 경우 도망 다니는 버튼을 만드는 방법입니다.
조건은 아래와 같습니다.
- 버튼이 랜덤 한 위치에 다시 그려져야 함
- 마우스가 클릭 한 범위를 벗어나 다르곳에 위치하게 함
- 화면을 벗어나지 않아야 하고 벗어난 경우 가운데로 위치하도록
아래 스크립트를 버튼에 추가합니다.
using UnityEngine;
using UnityEngine.EventSystems;
public class ButtonEscape : MonoBehaviour, IPointerEnterHandler
{
public float escapeDistance = 150f; // 버튼이 이동할 거리
public void OnPointerEnter(PointerEventData eventData) // 마우스 오버 이벤트 처리
{
MoveButton();
}
private void MoveButton()
{
RectTransform rectTransform = GetComponent<RectTransform>();
// 현재 마우스 위치를 화면 좌표계로 변환
Vector3 mousePosition = Input.mousePosition;
Vector3 screenPoint = Camera.main.ScreenToWorldPoint(mousePosition);
// 버튼의 새 위치 계산
Vector2 newPosition = CalculateNewPosition(rectTransform.anchoredPosition, screenPoint);
// 버튼 위치 업데이트
rectTransform.anchoredPosition = newPosition;
}
private Vector2 CalculateNewPosition(Vector2 buttonPosition, Vector2 mousePosition)
{
// 버튼과 마우스 위치 사이의 방향 벡터 계산
Vector2 direction = (buttonPosition - new Vector2(mousePosition.x, mousePosition.y)).normalized;
// 방향 벡터에 거리를 곱하여 새 위치 계산
Vector2 potentialPosition = buttonPosition + direction * escapeDistance;
// 화면 경계 검사
bool isOutsideHorizontalBounds = potentialPosition.x < -Screen.width / 2 || potentialPosition.x > Screen.width / 2;
bool isOutsideVerticalBounds = potentialPosition.y < -Screen.height / 2 || potentialPosition.y > Screen.height / 2;
// 화면 경계를 벗어나면 중앙으로 이동
if (isOutsideHorizontalBounds || isOutsideVerticalBounds)
{
return new Vector2(0, 0); // 화면 중앙
}
return potentialPosition;
}
}
적용한 결과 입니다.
버튼에 마우스를 가져다 대면 버튼의 위치가 마우스 위치에서 벗어나 위치가 바뀌고 화면의 경계를 벗어나면 버튼이 가운데로 오는 걸 확인할 수 있습니다.
[Unity] 물체 잡기 (Grab Object) (0) | 2024.01.13 |
---|---|
[Unity] [Collab] Collab service is deprecated and has been replaced with PlasticSCM 에러 처리방법 (0) | 2024.01.09 |
[Unity] 카메라 흔들기 (Camera Shake) 하기 (0) | 2023.12.14 |
[Unity] Visual Scripting - 구름 흐르게 하기 (사물 자동 이동) (0) | 2023.12.13 |
[Unity] Mouse Drag 로 Main Camera 이동하기 (Drag and Move Camera) (0) | 2023.12.13 |