zoukankan      html  css  js  c++  java
  • 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);
        }
    }
  • 相关阅读:
    JavaScript面试库
    JS事件委托的原理和应用
    缓存ABC
    网络模型探究
    持续集成配置之Nuget
    angular应用容器化部署
    微服务随想
    .NET性能优化小技巧
    博客园博客小优化
    Emmet 简介
  • 原文地址:https://www.cnblogs.com/DazeJiang/p/14612766.html
Copyright © 2011-2022 走看看