您的位置:首页 > 移动开发 > Unity3D

Unity 实现鼠标拖拽查看地图

2017-08-07 17:54 323 查看
游戏开发过程中,地图(例如RPG地图)往往比摄像机尺寸大,玩家需要通过滑动来查看地图。下面实现通过鼠标滑动来查看地图。

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上测试通过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: