移动设备上的 2D 光线投射会产生奇怪的结果
2D raycast on mobile is giving weird results
我正在尝试检测我正在使用 Unity 开发的原型中对撞机的简单点击。问题是,虽然它检测到碰撞,但有时似乎偏离了目标。
这是我的
Vector2 point = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D hit = Physics2D.Raycast(point, Vector2.zero);
if (hit.collider != null)
{
//Do stuff
}
我预计它只会在对撞机上单独运行。
我添加了一些文本日志以确保它不会影响其他内容。
这里有一张小图来解释。蓝色是应该识别敲击的地方,红色是我用手指敲击的地方,它仍然像我敲击蓝色一样识别它。 https://gyazo.com/7462de174d30b2d81a30c17f2bbc62fa
尝试这样的事情:
Vector3 screenTouchPos = Input.GetTouch(0).position;
screenTouchPos.z = 1f; // distance to the camera
Vector2 point = Camera.main.ScreenToWorldPoint(screenTouchPos);
此处说明:ScreenToWorldPoint() not working
ScreenToWorldPoint receives a Vector3 argument where x and y are the screen coordinates, and z is the distance from the camera. Since Input.mousePosition.z is always 0, what you're getting is the camera position.
精度:这应该只是 perspective 相机投影的问题,而不是 orthographic 投影的问题。
编辑:由于这不能解决您的问题,这里有一些调试技巧(我没有足够的信息来提供任何建议):
- 使用
Debug.DrawLine
检查Vector2 point
是否有正确的值
- 如果是这样,请检查您的碰撞器是否具有正确的 size/position。
- 如果不对,用
Camera.ViewportPointToRay
配合Debug.DrawLine
看射线是否正确
好的,我发现了问题。我将 post 放在这里以防其他人遇到此类问题并且似乎无法正常工作。
简单地说,检查你的相机变换。我的不知何故在 Y 中有一个偏移量 1,它把一切都搞砸了。
我正在尝试检测我正在使用 Unity 开发的原型中对撞机的简单点击。问题是,虽然它检测到碰撞,但有时似乎偏离了目标。
这是我的
Vector2 point = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D hit = Physics2D.Raycast(point, Vector2.zero);
if (hit.collider != null)
{
//Do stuff
}
我预计它只会在对撞机上单独运行。 我添加了一些文本日志以确保它不会影响其他内容。
这里有一张小图来解释。蓝色是应该识别敲击的地方,红色是我用手指敲击的地方,它仍然像我敲击蓝色一样识别它。 https://gyazo.com/7462de174d30b2d81a30c17f2bbc62fa
尝试这样的事情:
Vector3 screenTouchPos = Input.GetTouch(0).position;
screenTouchPos.z = 1f; // distance to the camera
Vector2 point = Camera.main.ScreenToWorldPoint(screenTouchPos);
此处说明:ScreenToWorldPoint() not working
ScreenToWorldPoint receives a Vector3 argument where x and y are the screen coordinates, and z is the distance from the camera. Since Input.mousePosition.z is always 0, what you're getting is the camera position.
精度:这应该只是 perspective 相机投影的问题,而不是 orthographic 投影的问题。
编辑:由于这不能解决您的问题,这里有一些调试技巧(我没有足够的信息来提供任何建议):
- 使用
Debug.DrawLine
检查Vector2 point
是否有正确的值- 如果是这样,请检查您的碰撞器是否具有正确的 size/position。
- 如果不对,用
Camera.ViewportPointToRay
配合Debug.DrawLine
看射线是否正确
好的,我发现了问题。我将 post 放在这里以防其他人遇到此类问题并且似乎无法正常工作。
简单地说,检查你的相机变换。我的不知何故在 Y 中有一个偏移量 1,它把一切都搞砸了。