요번 카메라관련 소스에는 굉장히 유용한 함수와 기법들이 들어가있다.
카메라가 플레이어를 쫒아다니는 형식으로, 다른 곳에서도 유용하게 사용할 수 있을 것 같다.
using UnityEngine; using System.Collections; public class CameraPoint : MonoBehaviour { public float xMargin = 1f; //X축을 캐릭터가 카메라 내부에서 이동할 수 있는 범위 public float yMargin = 1f; //Y축을 캐릭터가 카메라 내부에서 이동할 수 있는 범위 public float xSmooth = 2f; //카메라 X축 이동속도 public float ySmooth = 2f; //카메라 Y축 이동속도 public float maxY = 5; //Y축이 이동할 수 있는 최대값 public float minY = -5; //Y축이 이동할 수 있는 최소값 private float targetX; private float targetY; private Transform player; //카메라 조준 오브젝트 // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void Awake() { //하이어라키뷰의 CameraPoint 오브젝트를 찾아 player에 연결한다. player = GameObject.Find("CameraPoint").transform; } void FixedUpdate() { TrackPlayer(); } bool CheckXMargin() { return Mathf.Abs(transform.position.x - player.position.x) > xMargin; } bool CheckYMargin() { return Mathf.Abs(transform.position.y - player.position.y) > yMargin; } void TrackPlayer() { //카메라 위치값 X, Y변수에 연결 targetX = transform.position.x; targetY = transform.position.y; //캐릭터가 카메라의 X값을 벗어나면 targetX의 수치를 //캐릭터 위치로 부드럽게 이동시킨다. if(CheckXMargin()) { //선형 보간함수 //일정하게 쪼개서 점진적으로 변화시킴 //사용방법 //Mathf.Lerp(시작값, 끝값, 변화값) targetX = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.deltaTime); } //플레이어가 카메라의 Y값을 벗어나면 //targetY의 수치를 캐릭터 위치로 부드럽게 이동시킨다 if(CheckYMargin()) { targetY = Mathf.Lerp(transform.position.y, player.position.y, ySmooth * Time.deltaTime); } //카메라가 이동할 수 있는 Y값 범위 //최소 최대치 고정 //최소, 최대치를 넘어가지 않도록 고정하는 함수 //사용방법 //Mathf.Clamp(value, 최소값, 최대값) //value가 최소보다 작으면 최소값 리턴 //최대보다 크면 최대값 리턴 targetY = Mathf.Clamp(targetY, minY, maxY); //카메라의 이동 transform.position = new Vector3(targetX, targetY, transform.position.z); } }