Unity 实现鼠标拖拽查看地图
2017-08-07 17:54
323 查看
游戏开发过程中,地图(例如RPG地图)往往比摄像机尺寸大,玩家需要通过滑动来查看地图。下面实现通过鼠标滑动来查看地图。
![](https://oscdn.geek-share.com/Uploads/Images/Content/201908/15/aaba17f34a99dc998743f7d898d66bc1)
![](https://oscdn.geek-share.com/Uploads/Images/Content/201908/15/99c9a829fe4786f0b6015314e6d32867)
CameraController.cs
本方法和代码在Unity 2017上测试通过。
Step1: 新建一个GameObject,重命名为 GameBounds
Step2: 在GameBounds上添加Box Collider 2D组件,其大小为游戏地图的大小即可
原理图:Step3: 在MainCamera上添加下列脚本
CameraController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraController : MonoBehaviour { Camera camera; public Vector2 Margin, Smoothing; public BoxCollider2D Bounds; private Vector3 _min, _max; private Vector2 first = Vector2.zero;//鼠标第一次落下点 private Vector2 second = Vector2.zero;//鼠标第二次位置(拖拽位置) private Vector3 vecPos = Vector3.zero; private bool IsNeedMove = false;//是否需要移动 private void Awake() { } public void Start() { _min = Bounds.bounds.min;//包围盒 _max = Bounds.bounds.max; first.x = transform.position.x;//初始化 first.y = transform.position.y; } public void OnGUI() { if (Event.current.type == EventType.MouseDown) { //记录鼠标按下的位置 first = Event.current.mousePosition; } if (Event.current.type == EventType.MouseDrag) { //记录鼠标拖动的位置 second = Event.current.mousePosition; Vector3 fir = Camera.main.ScreenToWorldPoint(new Vector3(first.x, first.y,0));//转换至世界坐标 Vector3 sec = Camera.main.ScreenToWorldPoint(new Vector3(second.x, second.y, 0)); vecPos = sec - fir;//需要移动的 向量 first = second; IsNeedMove = true; } else { IsNeedMove = false; } } public void Update() { if (IsNeedMove == false) { return; } var x = transform.position.x; var y = transform.position.y; x = x - vecPos.x;//向量偏移 y = y + vecPos.y; var cameraHalfWidth = Camera.main.orthographicSize * ((float)Screen.width / Screen.height); //保证不会移除包围盒 x = Mathf.Clamp(x, _min.x + cameraHalfWidth, _max.x - cameraHalfWidth); y = Mathf.Clamp(y, _min.y + Camera.main.orthographicSize, _max.y - Camera.main.orthographicSize); transform.position = new Vector3(x, y, transform.position.z); } }
本方法和代码在Unity 2017上测试通过。
相关文章推荐
- unity实现鼠标拖拽缩放功能代码
- 【狼】unity 鼠标拖拽物体实现任意角度自旋转
- unity 鼠标拖拽物体实现任意角度自旋转
- unity实现鼠标点击后拖拽物体
- 在unity中用鼠标实现在场景中拖动物体,用鼠标滚轮实现缩放
- 实现简单的鼠标拖拽事件
- 用javascript实现既能禁止页面鼠标右键查看 同时又能查看页面文本框右键菜单
- Java3D读取3DMax模型并实现鼠标拖拽、旋转、滚轮缩放等功能
- unity使用IDragHandler实现拖拽
- unity 原生UI 拖拽跟随鼠标移动
- js实现登录框鼠标拖拽效果
- 如何实现鼠标拖拽窗口
- js div拖拽实现兼容ie/firefox js之鼠标位置深入解析
- 在unity中用鼠标实现在场景中拖动物体,用鼠标滚轮实现缩放
- 【java】实现JPanel鼠标拖拽
- Unity用鼠标实现在场景中拖动物体,用鼠标滚轮实现缩放
- 如何重写PictureBox的OnPaint方法绘制矩形,并实现拖动改变矩形大小,鼠标悬停时提示拖拽方向(二)
- 使用b2MouseJoint实现鼠标拖拽刚体的效果
- unity--鼠标画线、画图实现
- js实现鼠标拖拽