zoukankan      html  css  js  c++  java
  • Unity小地图Map

    从网上搜了一下,基本上的Map都是通过一些屏幕宽度跟鼠标位置计算出相对位置,然后根据地图的比例算出来的,这样的地图只能靠近屏幕的角落(当然不排除可以把另外一部分减去也可以)

    今天我提供一个另外思路的Map,废话少说,直接上的代码

    思路为把鼠标位置转为UGUI位置,然后把此位置跟UI地图作比较,然后根据比例算出位置

    1、创建RenderTexture,命名为Map,设置大小为256x256,当然设置16:9的也可以,但是一定要跟MapCamera对上

    2、创建RawImage放置第一步创建的RenderTexture的Map,大小设置为256x256

    3、创建MapCamera,设置视口等属性

    3、创建地块,创建Target,在Target里面创建一个Canvas并设置成为世界UI

    4、把需要MapCamera显示的物体设置成同一个层级(Layer),我这里设置的事Map

    5、最后看一下定位的代码

    public class MapManager : MonoBehaviour
    {
        [SerializeField]
        private Canvas canvas;
    
        [SerializeField]
        private Vector2 mapRtSize;    //RT大小,或者自动获取RT的Size
    
        [SerializeField]
        private Vector2 mapSize;     //地图大小
    
        [SerializeField]
        private Transform target;
    
        private Vector2 mapScale;    //地图缩放比例
        private void Start()
        {
            mapScale = mapRtSize / mapSize;
        }
    
        private void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Vector2 pos;
                RectTransform rt = canvas.transform as RectTransform;
                if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rt, Input.mousePosition, canvas.worldCamera, out pos))
                {   //鼠标位置转为UGUI位置
    
                    pos = pos - GetComponent<RectTransform>().anchoredPosition;
                    Debug.Log(pos);
                    if (Math.Abs(pos.x) > mapRtSize.x/2)   //限制位置
                    {
                        pos = new Vector2(mapRtSize.x/2, pos.y);
                    }
                    if (Math.Abs(pos.y) > mapRtSize.y/2)
                    {
                        pos = new Vector2(pos.x, mapRtSize.y/2);
                    }
                    target.position = new Vector3(pos.x/mapScale.x, 0, pos.y/mapScale.y);
                }
            }
        }
    
    }

    6、最后上传一下工程(版本Unity2018.3.14f1)

     https://files.cnblogs.com/files/ZhiXing-Blogs/Map.zip

  • 相关阅读:
    python+selenium webdriver.firefox()方式配置浏览器设置
    spring框架学习之依赖注入(二)
    spring框架体系结构介绍
    mongoDB数据更新与操作符
    mongoDB学习笔记<一>
    关于IOS AFNetWorking内存泄漏的问题
    IOS 11 下适配UITableView
    调试Xamarin.Android时出现缺少"Mono.Posix 2.0.0"的错误
    EF6 MySQL错误之“Specified key was too long; max key length is 767 bytes”
    Webstrom安装+激活
  • 原文地址:https://www.cnblogs.com/ZhiXing-Blogs/p/12955879.html
Copyright © 2011-2022 走看看