오류 발생
캐릭터가 바라보는 방향을 마우스가 움직이는 방향과 일치하게끔 만들기 위해 코드 수정 중 발생함.
다음과 같이 과하게 회전하는 현상 발생.
마우스를 멈췄음에도 계속 회전하게 됨.
오류 수정 과정
더보기
문제가 되는 코드.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Cam")]
public GameObject VirtualCam;
public GameObject PinPoint;
private Vector3 viewVector;
private void Update()
{
CheckCameraRotation();
}
//카메라 방향 확인.
private void CheckCameraRotation()
{
// 카메라와 플레이어 사이의 벡터.
viewVector = VirtualCam.transform.position - PinPoint.transform.position;
// 방향 벡터로부터 회전 값 계산.
Quaternion rotation = Quaternion.LookRotation(viewVector);
// Transform의 rotation 값 설정.
transform.rotation = rotation;
}
}
카메라의 방향과 회전축(캐릭터)의 사이의 방향 벡터로 플레이어가 바라보는 방향을 계산해서 그 방향을 바라보게 하는것이 목표였으나 회전이 멈추지 않아서 실패했다.
물체의 transform.rotation을 바꾸는게 아니라, rb의 MoveRotation을 바꿔보기로 했다.
//카메라 방향 확인.
private void CheckCameraRotation()
{
// 카메라와 플레이어 사이의 벡터.
viewVector = VirtualCam.transform.position - PinPoint.transform.position;
// 방향 벡터로부터 회전 값 계산.
Quaternion rotation = Quaternion.LookRotation(viewVector);
// rotation 값 설정.
rb.MoveRotation(rotation);
//transform.rotation = rotation;
}
여전히 카메라가 주체가 안되는 모습이다.
이때 하이어라키 창을 보니 카메라가 움직이는 플레이어 안에 있는걸 발견했다.
이렇게 되면 카메라가 이동함-> 이동한 방향대로 부모인 Player가 이동함 -> 따라서 카메라도 한번 더 이동함
이런식으로 반복되게 된다.
따라서 부모 밖으로 카메라를 분리해주면,
부드럽게 움직이는 걸 볼 수 있다.
더보기
약간의 수정을 더 거친 뒤의 코드 전문
using System.Collections;
using System.Collections.Generic;
using UnityEngine.InputSystem;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
[Header("Setting")]
private Vector2 curMovementInput;
public float MoveSpeed;
[Header("Cam")]
public GameObject VirtualCam;
public GameObject PinPoint;
private Vector3 viewVector;
private Vector3 viewVectorTemp;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
Move();
CheckCameraRotation();
}
// 기본 움직임.
private void Move()
{
Vector3 dir = transform.forward * curMovementInput.y + transform.right * curMovementInput.x;
rb.position += dir * MoveSpeed * Time.unscaledDeltaTime;
}
// 기본 움직임 입력 값.
public void OnMove(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
curMovementInput = context.ReadValue<Vector2>();
}
else if (context.phase == InputActionPhase.Canceled)
{
curMovementInput = Vector2.zero;
}
}
//카메라 방향 확인.
private void CheckCameraRotation()
{
// 카메라와 플레이어 사이의 벡터.
viewVector = PinPoint.transform.position - VirtualCam.transform.position;
// 위 아래로는 안움직이도록 값 조절.
viewVector.y = 0;
// 방향 벡터로부터 회전 값 계산.
if (viewVector != viewVectorTemp)
{
viewVectorTemp = viewVector;
Quaternion rotation = Quaternion.LookRotation(viewVector);
rb.MoveRotation(rotation);
}
}
}
'유니티' 카테고리의 다른 글
오브젝트 풀링의 사용 (0) | 2024.09.22 |
---|---|
Occlusion Culling (시작 및 Bake) (0) | 2024.06.28 |
포톤 멀티 서버 만들기(PUN 2)_사용편 (0) | 2024.06.22 |
포톤 멀티 서버 만들기(PUN 2)_세팅편 (0) | 2024.06.21 |
유니티 3D Tilemap (1) | 2024.06.12 |