【Unity3D】Unity2D实现相机跟随物体移动(脚本可以挂在Camera上直接用)

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

public class CameraFollow : MonoBehaviour
{
    /// <summary>
    /// 
    /// CameraFollow说明
    ///
    /// 1.该脚本挂在Main Camera上;
    /// 2.游戏场景背景需要添加一个BoxCollider2D组件,碰撞体边缘根据实际背景边缘设置,然后拖到“BoxCollider2D 背景边缘”上;
    /// 3.Main Camera上需要添加一个BoxCollider2D组件,碰撞体边缘大小须调整跟窗口大小一致;
    /// 4.把主角拖到“Gameobject 主角”上;
    /// 5."主角到左右边缘最小距离"、"主角到上下边缘最小距离"可以调整判断主角到达相机边缘的最小距离;
    /// 
    /// </summary>
    private BoxCollider2D 相机边缘;
    private float x_cameralength,y_cameralength;
    private float x_相机左, x_相机右, y_相机上, y_相机下;
    private float x_背景左, x_背景右, y_背景上, y_背景下;
    private float x_主角, y_主角;

    public BoxCollider2D 背景边缘;
    public GameObject 主角;
    public float 主角到左右边缘最小距离;
    public float 主角到上下边缘最小距离;

    void Start()
    {
        相机边缘 = gameObject.GetComponent<BoxCollider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        GetMargin();

        if (x_相机左 > x_背景左)
        {
            FollowLeft();
        }
        if(x_相机右 < x_背景右)
        {
            FollowRight();
        }
        if(y_相机上 < y_背景上)
        {
            FollowUp();
        }
        if(y_相机下 > y_背景下)
        {
            FollowDown();
        }

    }


    public void GetMargin()
    {
        x_cameralength = 相机边缘.bounds.size.x;
        y_cameralength = 相机边缘.bounds.size.y;
        x_相机左 = 相机边缘.bounds.min.x;
        x_相机右 = 相机边缘.bounds.max.x;
        y_相机下 = 相机边缘.bounds.min.y;
        y_相机上 = 相机边缘.bounds.max.y;
        x_背景左 = 背景边缘.bounds.min.x;
        x_背景右 = 背景边缘.bounds.max.x;
        y_背景下 = 背景边缘.bounds.min.y;
        y_背景上 = 背景边缘.bounds.max.y;
        x_主角 = 主角.transform.position.x;
        y_主角 = 主角.transform.position.y;
    }

    public void FollowLeft()
    {
        if (x_主角 - 主角到左右边缘最小距离 < x_相机左)
        {
            transform.position = new Vector3(主角.transform.position.x + x_cameralength / 2 - 主角到左右边缘最小距离, this.transform.position.y, this.transform.position.z);
        }
    }
    public void FollowRight()
    {
        if (x_主角 + 主角到左右边缘最小距离 > x_相机右)
        {
            transform.position = new Vector3(主角.transform.position.x - x_cameralength / 2 + 主角到左右边缘最小距离, this.transform.position.y, this.transform.position.z);
        }
    }
    public void FollowUp()
    {
        if (y_主角 + 主角到上下边缘最小距离 > y_相机上)
        {
            transform.position = new Vector3(this.transform.position.x, 主角.transform.position.y - y_cameralength / 2 + 主角到上下边缘最小距离, this.transform.position.z);
        }
    }
    public void FollowDown()
    {
        if (y_主角 - 主角到上下边缘最小距离 < y_相机下)
        {
            transform.position = new Vector3(this.transform.position.x, 主角.transform.position.y + y_cameralength / 2 - 主角到上下边缘最小距离, this.transform.position.z);
        }
    }
}
原文地址:https://www.cnblogs.com/garychen97/p/14371509.html