상세 컨텐츠

본문 제목

[Unity] Player, Camera 회전

유니티

by simstealer 2022. 9. 21. 11:55

본문

1. 키보드로 입력받아 회전하기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField]
    private float _moveSpeed = 5f;
    [SerializeField]
    private float _rotationSpeed = 60f;
    private Rigidbody _rigidbody;

    private void Awake()
    {
        _rigidbody = GetComponent<Rigidbody>();
    }

    private void FixedUpdate()
    {
        // 이동
        float inputForward = Input.GetAxis("Vertical");
        Vector3 deltaPosition = inputForward * _moveSpeed * Time.fixedDeltaTime * transform.forward;
        _rigidbody.MovePosition(_rigidbody.position + deltaPosition);

        // 회전
        float inputRight = Input.GetAxis("Horizontal");
        float deltaRotationY = inputRight * _rotationSpeed * Time.fixedDeltaTime;
        _rigidbody.MoveRotation(_rigidbody.rotation * Quaternion.Euler(0f, deltaRotationY, 0f)); 
    }
}

 

2. 마우스로 입력받아 회전하기

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    // 민감도
    [SerializeField]
    private float lookSensitivity;

    // 카메라 한계
    [SerializeField]
    private float cameraRotationLimit;
    private float curruntCameraRotationY = 0;

    // 카메라 컴포넌트
    [SerializeField]
    private Camera theCamera;
    
    // 입력
    private Rigidbody rigidBody;

    void Start()
    {
        rigidBody = GetComponent<Rigidbody>();
        theCamera = GetComponentInChildren<Camera>();
    }

    void Update()
    {
        CameraRotation();
    }

    private void CameraRotation()
    {
        // 상하 카메라 회전
        float _xRotation = Input.GetAxisRaw("Mouse Y");
        // 마우스 Y 입력 값과 민감도를 곱하기
        float _cameraRotationX = _xRotation * lookSensitivity;
        curruntCameraRotationY -= _cameraRotationX;
        
        // 상하 카메라 범위 가두기
        // Mathf.Clamp() - 최소 값과 최대 값을 설정해서 범위 이외의 값을 넘지 않도록 한다
        // Mathf.Clamp(float value값, 최소값, 최대값)
        curruntCameraRotationY = Mathf.Clamp(curruntCameraRotationY, -cameraRotationLimit, cameraRotationLimit);
        
		// 카메라 포지션에 앵글 적용
        theCamera.transform.localEulerAngles = new Vector3(curruntCameraRotationX, 0f, 0f);
    }

    private void CharacterRotation()
    {
        // 좌우 케릭터 회전
        float _yRotation = Input.GetAxisRaw("Mouse X");
        // 케릭터의 위치와 민감도를 곱하기
        Vector3 _characterRotationY = new Vector3(0f, _yRotation, 0f) * lookSensitivity;
        // MoveRotation()으로 Y축 회전 적용
        rigidBody.MoveRotation(rigidBody.rotation * Quaternion.Euler(_characterRotationY));
    }
}

관련글 더보기

댓글 영역