Client/Unity

Unity) 3인칭 캐릭터 - 카메라

Juzdalua 2024. 5. 2. 15:17

셋팅)

FollowCamera와 Camera는 캐릭터의 가슴높이 정도로 위치를 조정한다.

 

스크립트)

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

public class CameraMovement : MonoBehaviour
{
    public Transform objectToFollow; // 따라갈 카메라
    public float followSpeed = 10f; // 카메라 속도
    public float sensitivity = 100f; // 마우스 감도
    public float clampAngle = 70f; // 상하 각도 제한
    public float smoothness = 10f;
    
    private float rotX;
    private float rotY;

    public Transform realCamera;
    public Vector3 direction;
    public Vector3 finalDirection;

    // 플레이어와 카메라 사이 물체가 있을 때, 카메라 거리 조정
    public float minDistance = 1f;
    public float maxDistance = 2f;
    public float finalDistance;


    // Start is called before the first frame update
    void Start()
    {
        rotX = transform.localRotation.eulerAngles.x;
        rotY = transform.localRotation.eulerAngles.y;
        direction = realCamera.localPosition.normalized;
        finalDistance = realCamera.localPosition.magnitude;

        // 커서 가리기
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        rotX -= Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
        rotY += Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;

        rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

        Quaternion rot = Quaternion.Euler(rotX, rotY, 0);
        transform.rotation = rot;
    }

    void LateUpdate() {
        transform.position = Vector3.MoveTowards(transform.position, objectToFollow.position, followSpeed * Time.deltaTime);
        finalDirection = transform.TransformPoint(direction * maxDistance);
        
        RaycastHit hit;
        if(Physics.Linecast(transform.position, finalDirection, out hit)){
            finalDistance = Mathf.Clamp(hit.distance, minDistance, maxDistance);
        } else{
            finalDistance = maxDistance;
        }

        realCamera.localPosition = Vector3.Lerp(realCamera.localPosition, direction * finalDistance, Time.deltaTime * smoothness);
    }
}

 

오브젝트 주입)

 

참고)

 

'Client > Unity' 카테고리의 다른 글

Unity) Input system - 이동  (0) 2024.05.04
Unity) 3인칭 캐릭터 - 이동  (0) 2024.05.02
Unity) Third Person Camera  (1) 2024.04.28
Unity) 3D - 캐릭터 이동  (0) 2024.04.26
Unity 기초 속성  (1) 2024.04.26