2D游戏的相机(限制相机视野在地图内)

挂载MapBoxColider的物体Position 设置为0,0,0,总体没什么难度。

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

public class CameraController2D : MonoBehaviour
{
    public Transform followTarget;
    public float speed = 1;
    public Vector2 cameraoffset = Vector2.zero;
    public Collider2D mapRange;
    float halfHeight, halfWeight;
    float mapleft, mapright, maptop, mapbottom;
    Camera mainCam;
    private void Start()
    {
        mapleft = mapRange.bounds.min.x;
        mapright = mapRange.bounds.max.x;
        maptop = mapRange.bounds.max.y; 
        mapbottom = mapRange.bounds.min.y;
        mainCam = GetComponent<Camera>();
        halfHeight = mainCam.orthographicSize;
        halfWeight = mainCam.orthographicSize * mainCam.aspect;
    }
    private void LateUpdate()
    {
        Vector3 targetPos = new Vector3(followTarget.transform.position.x+cameraoffset.x, followTarget.transform.position.y+cameraoffset.y, transform.position.z);
        if (targetPos.x<mapleft+halfWeight)
        {
            targetPos.x = mapleft + halfWeight;
        }
        if (targetPos.x>mapright-halfWeight)
        {
            targetPos.x = mapright - halfWeight;
        }
        if (targetPos.y>maptop-halfHeight)
        {
            targetPos.y = maptop - halfHeight;
        }
        if (targetPos.y<mapbottom+halfHeight)
        {
            targetPos.y = mapbottom + halfHeight;
        }
        transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime*speed);
    }
}
原文地址:https://www.cnblogs.com/DazeJiang/p/14612766.html