Unity_Metaverse
[Unity] 1인칭 시점 카메라 설정하기
channnnii
2022. 7. 20. 17:03
1. floor를 깔아주고
2. 4면에 벽을 쌓아올린다.
3. 플레이어를 만들고, 플레이어를 키보드로 조작할 스크립트 만들기.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float walkSpeed;
[SerializeField]
private float lookSensitivity;
[SerializeField]
private float cameraRotationLimit;
private float currentCameraRotationX;
[SerializeField]
private Camera theCamera;
private Rigidbody myRigid;
void Start()
{
myRigid = GetComponent<Rigidbody>(); // private
}
void Update() // 컴퓨터마다 다르지만 대략 1초에 60번 실행
{
Move(); // 1️ 키보드 입력에 따라 이동
CameraRotation(); // 2️ 마우스를 위아래(Y) 움직임에 따라 카메라 X 축 회전
CharacterRotation(); // 3️ 마우스 좌우(X) 움직임에 따라 캐릭터 Y 축 회전
}
private void Move()
{
float _moveDirX = Input.GetAxisRaw("Horizontal");
float _moveDirZ = Input.GetAxisRaw("Vertical");
Vector3 _moveHorizontal = transform.right * _moveDirX;
Vector3 _moveVertical = transform.forward * _moveDirZ;
Vector3 _velocity = (_moveHorizontal + _moveVertical).normalized * walkSpeed;
myRigid.MovePosition(transform.position + _velocity * Time.deltaTime);
}
private void CameraRotation()
{
float _xRotation = Input.GetAxisRaw("Mouse Y");
float _cameraRotationX = _xRotation * lookSensitivity;
currentCameraRotationX -= _cameraRotationX;
currentCameraRotationX = Mathf.Clamp(currentCameraRotationX, -cameraRotationLimit, cameraRotationLimit);
theCamera.transform.localEulerAngles = new Vector3(currentCameraRotationX, 0f, 0f);
}
private void CharacterRotation() // 좌우 캐릭터 회전
{
float _yRotation = Input.GetAxisRaw("Mouse X");
Vector3 _characterRotationY = new Vector3(0f, _yRotation, 0f) * lookSensitivity;
myRigid.MoveRotation(myRigid.rotation * Quaternion.Euler(_characterRotationY)); // 쿼터니언 * 쿼터니언
// Debug.Log(myRigid.rotation); // 쿼터니언
// Debug.Log(myRigid.rotation.eulerAngles); // 벡터
}
}
문제점 1. Player가 벽을 뚫고 지나간다.
Player에 Rigidbody 컴포넌트를 추가해서, 물리엔진의 영향을 받을 수 있게 해주어야 합니다.
문제점 2. Player가 벽을 뚫고 지나가진 않지만, 벽에 부딪히면 넘어진다.
Rigidbody에서
Constraints의 Freeze Rotation 항목 체크해주기.