상세 컨텐츠

본문 제목

유니티 3D 비행기(캐릭터) 상하좌우 움직이기

유니티/기능

by MJ_119 2024. 8. 29. 17:17

본문

@ 비행기가 정면을 바라보게끔 하고 상하좌우 이동할 때 기체를 회전하며 움직이기 

 

using UnityEngine;

public class PlayerFly : MonoBehaviour
{
    float xInput, yInput;

    [SerializeField] float xLimit = 5f;
    [SerializeField] float yLimit = 5f;
    [SerializeField] float playerSpeed = 25f;
    [SerializeField] float pitchFacter = -2f;
    [SerializeField] float controllFactor = -15f;
    [SerializeField] float yawPitchFacter = 5f;

    [SerializeField] float controllRollFactor = -15f;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        MovePlayer();
        RotatePlayer();
    }

    void RotatePlayer()
    {
        float pitch = transform.localPosition.y * pitchFacter + yInput * controllFactor;
        float yaw = transform.localPosition.x * yawPitchFacter;
        float roll = xInput * controllRollFactor;

        transform.localRotation = Quaternion.Euler(pitch + 90f, yaw, roll);    
    }

    private void MovePlayer()
    {
        xInput = Input.GetAxis("Horizontal");
        yInput = Input.GetAxis("Vertical");

        float X = xInput * Time.deltaTime * playerSpeed;
        float Y = yInput * Time.deltaTime * playerSpeed;

        float moveX = transform.localPosition.x + X;
        float moveY = transform.localPosition.y + Y;

        float clampX = Mathf.Clamp(moveX, -xLimit, xLimit);
        float clampY = Mathf.Clamp(moveY, -2.5f, yLimit);

        transform.localPosition = new Vector3(clampX, clampY, transform.localPosition.z);
    }
}

전체 동작 설명

  • 이 함수는 플레이어의 위치와 사용자 입력을 기반으로 플레이어의 회전을 설정합니다.
  • pitch는 플레이어의 Y축 위치와 사용자 입력에 따라 위아래 회전을 계산하고, yaw는 X축 위치에 따라 좌우 회전을 계산합니다.
  • 마지막으로, roll은 사용자 입력에 따라 좌우 기울기를 계산합니다.
  • 계산된 피치, 요, 롤 값을 적용해 플레이어의 회전 상태를 설정합니다.

예시 시나리오

이 코드는 비행기나 우주선과 같은 3D 객체를 제어할 때 자주 사용되는 방식입니다. 예를 들어, 비행기의 경우:

  • pitch는 비행기의 머리를 위아래로 돌리는 동작(상하 이동)입니다.
  • yaw는 비행기를 좌우로 회전시키는 동작입니다.
  • roll은 비행기가 좌우로 기울어지며 회전하는 동작입니다.

이 함수는 이러한 3D 객체의 방향을 사용자의 입력에 따라 유연하게 조정해 줍니다.

 

- pitch값에 + 90f 을 한 이유 : 캐릭터가 기본방향이 위를 향해있기 때문

- 90을 더해주면 비행하는 것처럼 날아다니게 보임

 

관련글 더보기