KeiStory

728x90
반응형

Mouse Drag 로 Main Camera 이동하기 (Drag and Move Camera)

 

버튼을 클릭하여 카메라를 이동하고 있었는데 폰으로 배포하니 터치 드레그로 움직이는 게 필요해서 찾은 방법입니다.

아래는 기본적인 코드로 Mouse Drag 로 Main Camera 이동하는 Script  입니다.

using UnityEngine;
 
public class CameraDrag : MonoBehaviour
{
    public float dragSpeed = 2;
    private Vector3 dragOrigin;
  
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            dragOrigin = Input.mousePosition;
            return;
        }
 
        if (!Input.GetMouseButton(0)) return;
 
        Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
        Vector3 move = new Vector3(pos.x * dragSpeed, 0, pos.y * dragSpeed);
 
        transform.Translate(move, Space.World);  
    }
}

위 Script 를 Main Camera 에 추가하면 됩니다.

하지만 위코드는 아래처럼 화면을 벗어나도 계속 Main Camera 가 이동됩니다.

이를 막기위한 코드는 아래와 같습니다.

using UnityEngine;

public class CameraDrag : MonoBehaviour
{
    public float dragSpeed = 2;
    private Vector3 dragOrigin;

    /// <summary>
    /// Mouse Drag 여부
    /// </summary>
    private bool cameraDragging = false;

    /// <summary>
    /// Mouse Drag 벗어날 범위 (왼쪽)
    /// </summary>
    public float OuterLeft = -10f;
    /// <summary>
    /// Mouse Drag 벗어날 범위 (오른쪽)
    /// </summary>
    public float OuterRight = 10f;


    void Update()
    {
        Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

        float left = Screen.width * 0.2f;
        float right = Screen.width - (Screen.width * 0.2f);

        if (mousePosition.x < left)
        {
            cameraDragging = true;
        }
        else if (mousePosition.x > right)
        {
            cameraDragging = true;
        }

        if (cameraDragging)
        {
            if (Input.GetMouseButtonDown(0))
            {
                dragOrigin = Input.mousePosition;
                return;
            }

            if (!Input.GetMouseButton(0)) return;

            Vector3 pos = Camera.main.ScreenToViewportPoint(Input.mousePosition - dragOrigin);
            Vector3 move = new Vector3(pos.x * dragSpeed, 0, 0);

            if (move.x > 0f)
            {
                if (this.transform.position.x < OuterRight)
                {
                    transform.Translate(move, Space.World);
                }
            }
            else
            {
                if (this.transform.position.x > OuterLeft)
                {
                    transform.Translate(move, Space.World);
                }
            }
        }
    }

}

위 코드를 이용하면 Mouse Drag 시 Drag 방향으로 Main Camera 가 이동됩니다.

OuterLeft, OuterRight 값을 조정하여 자신의 화면에 맞도록 값을 설정해야 합니다.

아래는 좌우로 Drag 하여 이동하는 예시입니다.

 

728x90
반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band