首页 > 其他 > 详细

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

时间:2021-04-03 09:28:38      阅读:21      评论:0      收藏:0      [点我收藏+]

技术分享图片

挂载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);
    }
}

 

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

原文:https://www.cnblogs.com/DazeJiang/p/14612766.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!