행복한 하루

[Unity] SmoothFollow.cs 가 없는 경우 본문

Unity/Programming

[Unity] SmoothFollow.cs 가 없는 경우

변화의 물결 2022. 1. 18. 20:04

 

안녕하세요.

 

  현재 "절대강좌 2018년 판" 책 내용을 Unity 2020.3.16f1 (64-bit) 버전으로 따라 해보고 있습니다. 버전이 달라서 메뉴가 다르거나 없는 것을 찾아가며 실행하고 있습니다.

  그중에 Main Camera가 객체(Player)를 자연스럽게 따라가는 기능이 필요하다는 내용이 있습니다. 그런데 현재 버전에는 나타나지 않아서 찾아본 내용 공유드립니다.


1. 책 내용과 다른 점

 <Smooth Follow.cs가 없는 경우>

 - 내용상에는 Assets 메뉴 안에 Import package, Utility에 SmoothFollow.cs를 추가하라고 했지만, 실제 메뉴에는 없었습니다.

   현재 버전에서는 Import Package 에는 Custom Package라고 나옵니다. 그래서 책 내용을 따라 할 수 있는 것을 찾아보았습니다.

2. 해결 방법

 - 인터넷상에 고수분들이 많이 있어서 소스 참조할 수 있었습니다. (다른 소스들도 많이 있습니다.)

   간단하게 참조할 수 있는 소스가 있어서 사용하였습니다.

 - Project상에서 Create -> C# Script를 만들어서 소스를 추가를 합니다.(SmoothFollow.cs로 저장) 그리고 책 내용의 파일 구조처럼 "02. Script" 안에 옮겨놓습니다.

   

using UnityEngine;

public class SmoothFollow : MonoBehaviour
{
    public Transform target;
    public float distance = 10.0f;
    public float height = 5.0f;
    private float rotationDamping = 3.0f;
    private float heightDamping = 2.0f;

    void LateUpdate()
    {
        if (!target)
            return;

        var wantedRotationAngle = target.eulerAngles.y;
        var wantedHeight = target.position.y + height;
        var currentRotationAngle = transform.eulerAngles.y;
        var currentHeight = transform.position.y;

        currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
        currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime);

        var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0);

        transform.position = target.position;
        transform.position -= currentRotation * Vector3.forward * distance;
        transform.position = new Vector3(transform.position.x, currentHeight, transform.position.z);
        transform.LookAt(target);
    }
}

 - 참조 소스 -

 

 - Hierarchy 상에 Main Camera를 선택한 후 Inspector 상에 SmoothFollow 스크립트 파일을 Drag&Drop 합니다.

그러면 아래와 같이 속성(property)이 나타납니다.

 

 - Target 속성에는 Player 객체를 Drag&Drop 합니다. 그리고 Distance와 Height는 보면서 조절하시면 Player 객체를 거리와 높이 간격을 두고 따라가는 것을 확인할 수 있습니다.

 

감사합니다.

 

 

<참고 사이트>

1. [유니티 스크립트 소스] 지형 오브젝트를 부드럽게 따라다니는 오브젝트(카메라)

https://coderzero.tistory.com/entry/%EC%9C%A0%EB%8B%88%ED%8B%B0-%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EC%86%8C%EC%8A%A4-%EC%A7%80%ED%98%95-%EC%98%A4%EB%B8%8C%EC%A0%9D%ED%8A%B8%EB%A5%BC-%EB%B6%80%EB%93%9C%EB%9F%BD%EA%B2%8C-%EB%94%B0%EB%9D%BC%EB%8B%A4%EB%8B%88%EB%8A%94-%EC%98%A4%EB%B8%8C%EC%A0%9D%ED%8A%B8%EC%B9%B4%EB%A9%94%EB%9D%BC  

 

 

Comments