unity3d - unity拖拽世界位置
问题描述
我目前正在 Unity 中开发一个基本的纸牌游戏,但在弄清楚如何对我的纸牌进行拖动时遇到了一些麻烦。我目前的布局如下:
每当在我的卡片对象上检测到拖动事件时,我目前正在尝试使用该IDragHandler
接口接收回调。
我的最终目标是能够根据触摸/鼠标滑动的 x 轴将卡片向左/向右滑动。
我目前尝试使用传递给 OnDrag() IDragHandler 的 eventdata.delta 值来移动我的卡,但据我所知,这个值是以像素为单位的,当使用 Camera.main.ScreenToWorldPoint() 转换为世界单位时会导致值为 0,0,0。同样,尝试跟踪拖动开始的位置并减去当前位置会导致值 0,0,0。
我目前对如何使用世界单位拖动游戏对象有点茫然,所以如果有人能给我一些指导,我将不胜感激。
谢谢
编辑:
^这就是为什么你不应该在深夜使用 StackOverflow。
所以要添加一些额外的上下文:
- 卡片只是附加了网格渲染器和嵌入画布以添加文本的游戏对象(可能不是添加文本的最佳方式,但它有效)
- 卡片都在一个“手”对象下,该对象由一个用于接收事件的盒子 collider2d 和一个实现 IBeginDragHandler、IEndDragHandler 和 IDragHandler 的脚本组成
- 到目前为止,我已经尝试了两种不同的方法来计算阻力距离:
public void OnDrag(PointerEventData eventData)
{
Vector2 current = Camera.main.ScreenToWorldPoint(eventData.position);
Debug.Log("Current world position: "+current);
Vector3 delta = lastDragPoint - current;
// Store current value for next call to OnDrag
lastDragPoint = eventData.position;
// Now use the values in delta to move the cards
}
使用这种方法,我在调用后总是得到 0,0,0 的值,ScreenToWorldPoint
所以我无法移动卡片
我尝试过的第二种方法是:
public void OnDrag(PointerEventData eventData)
{
Vector3 screenCenter = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, 1f);
Vector3 screenTouch = screenCenter + new Vector3(eventData.delta.x, eventData.delta.y, 0f);
Vector3 worldCenterPosition = Camera.main.ScreenToWorldPoint(screenCenter);
Vector3 worldTouchPosition = Camera.main.ScreenToWorldPoint(screenTouch);
Vector3 delta = worldTouchPosition - worldCenterPosition;
// Now use the values in delta to move the cards
}
使用这种方法,我得到了更好的结果(卡片实际移动),但它们没有正确跟随鼠标。如果我拖动一张卡片,我将朝鼠标的方向移动,但是移动的距离明显小于鼠标移动的距离(即当鼠标到达屏幕边缘时,卡片只移动了一张卡片宽度)
解决方案
因此,在玩了一些游戏并检查了我从 ScreenToWorldPoint 的调用中收到的各种值之后,我终于找到了问题所在。在我第二次尝试的方法的代码中,我发现我在 ScreenToWorldPoint 中为 Z 参数使用了不正确的值。在做了一些研究之后,我发现他应该是相机和(我猜)触摸表面之间的 Z 距离。
Vector3 screenCenter = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, -Camera.main.transform.position.z);
Vector3 screenTouch = screenCenter + new Vector3(eventData.delta.x, eventData.delta.y, 0);
感谢所有花时间阅读我的问题的人。
推荐阅读
- excel - VBA在工作表更改中从目标获取列号
- excel - 根据时间的增加到达 Excel 中的特定单元格
- java - Java swing图形不更新
- javascript - Websocket棘轮codeigniter失败:连接建立错误:net :: ERR_CONNECTION_REFUSED
- c# - 如何使用 FtpCommand 获取系统类型之类的东西?
- algorithm - Raft 算法:术语何时增加?
- postgresql-10 - 如何在 Linux 服务器上的 PostgreSQL 数据库中进行备份和恢复
- ios - 如何裁剪给定矩形的图像视图
- tsql - MS SQL Server 2008 R2 表中插入操作的强度
- google-sheets - Countif 间接 Google 表格