unity3d - Unity - following finger only works for one direction
问题描述
I have made some code that should make my player move into the direction of the finger:
if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
Vector2 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 0));
if (pos.x < rb.position.x)
{
movehorizontal = -1;
}
if(pos.x > rb.position.x)
{
movehorizontal = 1;
}
if (pos.y < rb.position.z)
{
movevertical = -1;
}
if(pos.y > rb.position.z)
{
movevertical = 1;
}
}
Vector3 movement = new Vector3(movehorizontal, 0.00f, movevertical)*speed;
It's a 3D game, with a top-view, so my player starts at 0,0,0 and only moves along the x and z axis. My camera is positionated on 0,10,3. The following works on the x axis, so when my finger touches on the right side it goes to the right, if on the left to the left, but no matter where I touch it, it will only move to the front and not to the bottom of my screen.
I tried debugging, but the instructions werent working at the time.
解决方案
screentoWorldPoint 应存储为矢量3。此外,由于相机距离您的飞机 10 个单位,因此最后一个参数应为 10。
编辑,这只适用于直下的凸轮。无论相机角度如何,此代码都应该工作。
Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 1f));
Vector3 pointDelta = pos - Camera.main.transform.position;
float multiplier = -Camera.main.transform.position.y / pointDelta.y;
pos = Camera.main.transform.position + pointDelta * multiplier;
最后,这些行应该将 z 值相互比较
if (pos.z < rb.position.z)
if(pos.z > rb.position.z)
进行这些更改并让我们知道是否仍然存在任何其他问题
推荐阅读
- python - 如何在设置环境变量的同时导入 python 文件
- javascript - 如何追溯到“未捕获(承诺中)TypeError:无法读取属性'_currentElement' of null”?
- extjs - 如何向 itemselector 键映射 EXTjs 添加其他键?
- android - 从可绘制的画布位置到 Android 中的 WindowManager 矩阵或显示矩阵?
- python - 如何从列表列表中的键列表和值列表中创建字典列表
- github - 删除密码访问权限后,如何从命令行登录 GitHub?
- kubernetes - 如何将我的域指向我的 EKS 集群?
- sql - Oracle:根据更新的日期广告类似列获取最新交易
- angular - Ag-grid 对列数据进行排序,然后“发布”排序
- javascript - Javascript如何从选项选择中输出而不在空白页面中重新加载输出