티스토리 뷰

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를 입력해준다

 

배경의 넓이와 길이를 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
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함