Unity
[Unity] 플레이어 카메라 회전 기능
권벡터
2023. 6. 18. 23:23
코드
// 변수 선언부
private const float _threshold = 0.01f;
public GameObject CinemachineCameraTarget;
private float _cinemachineTargetPitch;
public float RotationSpeed;
public float TopClamp;
public float BottomClamp;
private float _rotationVelocity;
// 입력값이 마우스 값인지 판별하는 함수
bool IsCurrentDeviceMouse
{
get
{
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
return _playerInput.currentControlSchme == "KeyboardMouse";
#else
return false;
#endif
}
}
void start
{
_input = GetComponent<StartAssetInput>();
}
// 함수 실행부
Void CameraRotation()
{
// 입력값이 최소 입력 한계값을 넘겼을 때 아래 코드를 실행
if(_input.look.sqrMagnitude >= threshold)
{
// 마우스 입력값이 들어 올때는 deltaTime을 곱하지 않도록 한다.
float deltaTimeMultiplier = IsCurrentDeviceMouse ? 1.0f : Time.deltaTime;
// 카메라의 pitch값은 (마우스 입력값y) x (회전 속도)x (배수)
_cinemachimeTargetPitch += _input.look.y * RotationSpeed * deltaTimeMultiplier;
// 좌우 회전 값은 (마우스 입력값x) x (회전 속도) x(배수)
_rotationVelocity = _input.look.x * RotationSpeed * deltaTimeMultiplier;
// 카메라 pitch 각도를 일정 범위로 제한한다.
_cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);
// 카메라의 시점을 업데이트
CinemachineCameraTarget.transform.localRotation = Quaternion.Euler
(_cinemachineTargetPitch, 0.0f, 0.0f);
// 플레이어를 회전시킨다.
transform.Rotate(Vector3.up * _rotationVelocity);
}
}
참고
StarterAssetsInputs 스크립트의 look 분석
해당 함수들은 유니티 엔진의 InputSystem 부에서 입력값을 받으면 콜백 형식으로 실행되는 형식이다.
내가 만약 마우스를 움직였을 때, 그 때 움직였던 값들이 Vector2 자료형에 저장하는 방식으로 보인다.
// 변수 선언부
public Vector2 look;
public bool cursorInputForLook = true;
// 함수 실행부
public void OnLook(InputValue value)
{
if(cursorInputForLook)
{
LookInput(value.Get<Vector2>());
}
}
public void LookInput(Vector2 newLookDirection)
{
look = newLookDirection;
}
오랜만에 만져서 그런지 유니티가 자체적으로 InputSystem 을 만들어 놓은지는 몰랐다.
그래도 콜백 형식으로 만들어 넣으니 입력값을 일일이 Update 문에 갱신시키지 않아서 좋기는 하다.