반응형
저번에 만들어둔 미니맵을 바탕으로 스크립트 작업을 이어나갔다
설정이 더욱 중요하므로 보지 않았다면 아래 링크에서 보고 오시는 걸 추천한다
https://tears2am.tistory.com/44
0. 준비
- 빈게임오브젝트를 생성하고 MapController와 MapManager 2개의 스크립트를 생성한다
1. MapController
전체맵을 켜고 끄는 기능을 담은 스크립트다
using UnityEngine;
using UnityEngine.UI;
public class MapController : MonoBehaviour
{
public RawImage minimapImage;
public RawImage fullmapImage;
private KeyCode toggleMapKey = KeyCode.M;
private void Start()
{
minimapImage.gameObject.SetActive(true);
fullmapImage.gameObject.SetActive(false);
}
void Update()
{
if(Input.GetKeyDown(toggleMapKey))
ToggleMap();
}
private void ToggleMap()
{
bool isMiniMapActive = minimapImage.gameObject.activeSelf;
minimapImage.gameObject.SetActive(!isMiniMapActive);
fullmapImage.gameObject.SetActive(isMiniMapActive);
}
}
주의할 점 ( 헷갈리는 점 )
ToggleMap 함수에서 미니맵과 전체맵은 minimapImage의 상태에 맞춰 전환이 되게 만들었기에,
미니맵은 ! 연사자를 붙이고 전체맵은 ! 연산자를 붙이지 않는다
2. MapManager
- 전체맵을 켜면 드래그와 줌인줌아웃 기능이 가능하도록 만들었다
using UnityEngine;
using UnityEngine.UI;
public class MapManager : MonoBehaviour
{
public Camera mapCamera;
public RawImage fullMapImage;
private Vector2 mapSize;
// 전체맵 줌인 줌아웃
private float zoomSpeed = 3f;
private float oriZoom = 5f;
// 드래그
private Vector3 dragOrigin;
private bool isDragging = false;
private float currentZoom;
void Update()
{
if (gameObject.GetComponent<MapController>().fullmapImage.gameObject.activeSelf)
{
CalculateMapSize();
HandleMapZoom();
HandleMapDrag();
}
else
{
mapCamera.orthographicSize = oriZoom;
currentZoom = oriZoom;
mapCamera.transform.position = Camera.main.transform.position;
}
}
// 맵 크기 계산
private void CalculateMapSize()
{
// Raw Image의 실제 크기 계산
Rect rect = fullMapImage.rectTransform.rect;
Vector2 size = new Vector2(rect.width, rect.height);
Vector2 worldSize = size / fullMapImage.canvas.scaleFactor;
mapSize = worldSize / 2f;
}
// 맵 줌
private void HandleMapZoom()
{
// 마우스 휠 값
float scrollDelta = Input.mouseScrollDelta.y;
if (scrollDelta != 0)
{
if (currentZoom < oriZoom)
{
currentZoom = oriZoom;
}
currentZoom -= scrollDelta * zoomSpeed;
mapCamera.orthographicSize = currentZoom;
}
}
// 맵 드래그
private void HandleMapDrag()
{
if (Input.GetMouseButtonDown(0))
{
isDragging = true;
dragOrigin = mapCamera.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButtonUp(0))
{
isDragging = false;
}
if (isDragging)
{
Vector3 difference = dragOrigin - mapCamera.ScreenToWorldPoint(Input.mousePosition);
mapCamera.transform.position += difference;
}
}
}
3. 기본기능 완성
반응형
'유니티 > 기능구현' 카테고리의 다른 글
[Unity] 유니티 C#) 2D 게임 사다리(Ladder)와 피킹(Peeking) (1) | 2024.12.25 |
---|---|
[Unity] 유니티 C#) 메트로배니아 미니맵과 전체맵 ( 심화편 ) (1) | 2024.12.23 |
[Unity] 유니티 C#) 2D 매트로베니아 미니맵과 전체맵 ( 유니티 설정편 ) (0) | 2024.12.19 |
[Unity] 유니티 C#) FPS 주무기를 어떻게 구현할까? ( 저격총 ) (4) | 2024.10.27 |
[Unity] 유니티 C#) FPS 주무기를 어떻게 구현할까? ( 샷건 ) (0) | 2024.10.23 |