Unity3D 游戏开发:设置摄像机边界(10)

620 阅读1分钟

一、开发操作

1、给名为(CM vcam1)的Cinemachine相机添加CinemachineConfiner

image.png

2、创建空物体GameObject命名为Bounds为其添加组件(Component)Polygon Collider 2D

image.png

调整点的位置(Points)为

image.png

二、脚本编程

    using Cinemachine;
    using UnityEngine;

    public class SwitchBounds : MonoBehaviour
    {
    //TODO:切换场景后更改
    private void Start()
    {
    SwitchConfinerShape();
    }
    private void SwitchConfinerShape()
    {
    PolygonCollider2D confinerShape =GameObject.FindGameObjectWithTag("BoundsConfiner").GetComponent<PolygonCollider2D>();

            CinemachineConfiner confiner =GetComponent<CinemachineConfiner>();

            confiner.m_BoundingShape2D = confinerShape;


            //清除缓存
            confiner.InvalidatePathCache();
        }

    }

GameObject.FindGameObjectWithTag是Unity的一个方法,用于查找具有指定标签的单个游戏对象。它可以接受一个字符串参数,该参数为要查找对象的标签名称,并返回具有该名称标签的对象。当场景中存在多个具有相同标签的对象时,该方法只返回第一个匹配项。如果未找到具有该标签名称的任何对象,则返回null。

InvalidatePathCache()是一个CinemachineConfiner组件的方法,用于清除边界路径缓存。当相机限制范围发生变化时,需要使用该方法来更新边界路径缓存,以确保相机限制范围可以正确地应用于场景中。