IT/UNITY(C#)
(C#) Unity_플레이어를 따라오는 카메라 구현 (2D)
KS짱짱맨
2022. 7. 26. 14:28
2D게임에서
맵이 게임화면보다 클경우에, 화면을 플레이어 중심으로 비춰줄 필요가 있다.
배울것
- Mathf.Clamp (value, min, max) : 최소값과 최대값을 넘지 않는 value를 반환
- Vector3.Lerp(현위치, 목표위치, 걸리는 시간) : 목표 위치 까지 일정 시간동안 이동 (부드러운 움직임)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
public Transform playerTf;
public float speed = 3f;
public Vector2 offset;
public float mapWidth, mapHeight;
private float minX, maxX, minY, maxY;
float camWidth, camHeight;
private Camera cam;
private void Start() {
cam = Camera.main;
camWidth = cam.aspect * cam.orthographicSize;
camHeight = cam.orthographicSize;
minX = -(mapWidth/2);
maxX = mapWidth/2;
minY = -(mapHeight/2);
maxY = mapHeight/2;
}
private void FixedUpdate(){
float camX = Mathf.Clamp(playerTf.position.x+offset.x, minX+camWidth, maxX-camWidth);
float camY = Mathf.Clamp(playerTf.position.y+offset.y, minY+camHeight, maxY-camHeight);
Vector3 targetPos = new Vector3 (camX, camY, -10);
transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime*speed);
}
}
1. 메인 카메라에 위에 작성한 CameraMove 스크립트를 추가해준다.
2. mapWidth와 mapHeight를 입력해준다
단, 주의할점은 배경화면(맵)의 위치가 (0,0,0)이어야 한다!!!
3. 마지막으로 플레이어의 Transform을 끌어다가 스크립트의 PlayerTf에 할당해주고,
플레이 해보면 잘 된다.
끝.
참고 싸이트
https://hoil2.tistory.com/31
화면 높이 = 2 * Camera.main.orthographicSize
화면 넓이 = 2 * (화면 높이 * Camera.main.aspect)
Left,Top 좌표 = -화면 넓이/2, 화면 높이/2
Left,Bottom 좌표 = -화면 넓이/2, -화면 높이/2
Right,Top 좌표 = 화면 넓이/2, 화면 높이/2
Right,Bottom 좌표 = 화면 넓이/2, -화면 높이/2
728x90