실행 이미지

 

 

메인 카메라를 기준으로 상하좌우 방향 지정

 

** Cinemachine Virtual Camera - Body - Binding Mode = Wolrd Space 지정 **

 

using UnityEngine;

// 플레이어 캐릭터를 사용자 입력에 따라 움직이는 스크립트
public class PlayerMovement : MonoBehaviour {
    public float moveSpeed = 5f; // 앞뒤 움직임의 속도
    public float rotateSpeed = 180f; // 좌우 회전 속도

    private Rigidbody playerRigidbody; // 플레이어 캐릭터의 리지드바디
    private Animator playerAnimator; // 플레이어 캐릭터의 애니메이터

    private Camera mainCamera; // 메인 카메라

    private Vector3 saveInputMove;

    private void Start() {
        // 사용할 컴포넌트들의 참조를 가져오기
        playerRigidbody = GetComponent<Rigidbody>();
        playerAnimator = GetComponent<Animator>();

        mainCamera = Camera.main; // 메인 카메라를 찾습니다.
    }

    // FixedUpdate는 물리 갱신 주기에 맞춰 실행됨
    private void FixedUpdate() {
        // 물리 갱신 주기마다 움직임, 회전, 애니메이션 처리 실행
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        saveInputMove = new Vector3(moveHorizontal, 0, moveVertical);

        // 카메라의 방향에 기반한 이동 방향 계산
        Vector3 cameraForward = mainCamera.transform.forward;
        Vector3 cameraRight = mainCamera.transform.right;

        // 카메라가 바라보는 방향에서의 Y축 영향 제거
        cameraForward.y = 0;
        cameraRight.y = 0;
        cameraForward.Normalize();
        cameraRight.Normalize();

        // 최종 이동 벡터 계산
        Vector3 movement = (cameraForward * moveVertical + cameraRight * moveHorizontal) * moveSpeed;

        // Rigidbody를 이용하여 캐릭터 이동
        playerRigidbody.velocity = movement;

        if (movement != Vector3.zero)
        {
            // 캐릭터가 이동 방향을 바라보도록 회전
           Vector3 targetDirection = playerRigidbody.position + movement;
           transform.LookAt(targetDirection);
        }

        playerAnimator.SetFloat("Move", saveInputMove.magnitude);
    }

}
반응형

+ Recent posts