유니티 C# 모바일 스와이프 3D 오브젝트 회전시키기 간단 구현

반응형

코드 작성

using UnityEngine;

public class Swipe3D : MonoBehaviour
{
    private Vector2 startTouchPosition;
    private float zRotationSpeed = 0f; // Z축 회전 속도
    private float smoothTime = 1.0f; // Z축 회전을 1초 안에 0으로 줄이는 시간
    private float timeElapsed = 0f;  // 경과 시간 추적 변수
    private bool isSwiping = false;  // 스와이프 중인지 여부를 확인하는 변수

    void Update()
    {
        Vector2 deltaPosition = Vector2.zero;

        // 터치 입력 처리
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            switch (touch.phase)
            {
                case TouchPhase.Began:
                    // 터치 시작 위치 저장
                    startTouchPosition = touch.position;
                    isSwiping = true; // 스와이프 시작
                    break;

                case TouchPhase.Moved:
                    // 터치가 움직일 때 Z축 회전 속도 조정
                    deltaPosition = touch.position - startTouchPosition;
                    zRotationSpeed = deltaPosition.x * 0.1f; // 스와이프 거리의 비율 조정
                    break;

                case TouchPhase.Ended:
                    // 터치가 끝났을 때 스와이프 종료
                    isSwiping = false;
                    timeElapsed = 0f; // 스와이프 종료 시 경과 시간 초기화
                    break;
            }
        }
        else
        {
            // 마우스 입력 처리
            if (Input.GetMouseButtonDown(0))
            {
                // 마우스 버튼 클릭 시작 위치 저장
                startTouchPosition = Input.mousePosition;
                isSwiping = true; // 스와이프 시작
            }
            else if (Input.GetMouseButton(0))
            {
                // 마우스 버튼 클릭 중 이동
                deltaPosition = (Vector2)Input.mousePosition - startTouchPosition;
                zRotationSpeed = deltaPosition.x * 0.1f; // 스와이프 거리의 비율 조정
            }
            else if (Input.GetMouseButtonUp(0))
            {
                // 마우스 버튼 클릭이 끝났을 때 스와이프 종료
                isSwiping = false;
                timeElapsed = 0f; // 스와이프 종료 시 경과 시간 초기화
            }
        }

        // Z축 회전 속도를 적용하여 오브젝트 회전
        if (isSwiping)
        {
            float currentRotationZ = transform.eulerAngles.z;
            currentRotationZ += zRotationSpeed * Time.deltaTime * 20f; // 회전 속도 조정
            transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, currentRotationZ);
        }
        else
        {
            // 스와이프가 끝난 후 Z축 회전을 0으로 부드럽게 되돌리기
            if (timeElapsed < smoothTime)
            {
                timeElapsed += Time.deltaTime;
                float progress = Mathf.Clamp01(timeElapsed / smoothTime);

                // Z축 회전 값을 0으로 선형적으로 줄이기
                float currentRotationZ = transform.eulerAngles.z;
                currentRotationZ = Mathf.LerpAngle(currentRotationZ, 0f, progress);
                transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, currentRotationZ);
            }
        }
    }
}

 

반응형