如何立即将我的游戏对象移动到触摸的屏幕部分?
How can I move my GameObject instantly to part of screen that is touched?
我遇到了麻烦。我想简单地将我的游戏对象立即(无动画)移动到触摸的屏幕部分。我不希望对象是可拖动的。我只希望用户能够通过触摸屏幕上的区域来移动对象,而不是拖动。在我的代码中,它正在检测触摸,但只要我触摸屏幕上的某处,对象就会消失(在我的 iOS phone 上测试)。这是一个2D游戏。我不确定这是否会影响它,但对于我的游戏,相机总是向下移动。
这是在我的 Update() 函数中:
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0));
transform.position = touchPosition;
}
我猜问题出在您将深度指定为 0。
让 C 成为您的相机。你的相机会观察 space 并渲染它能看到的所有物体,只要物体不是离得太远 (d > far) 并且不太近 (d < 附近)。
当你打电话给
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(
new Vector3(touch.position.x, touch.position.y, 0));
你基本上是说:我需要找到一个位于射线上的点,从 C (Camera.main
) 开始并向 M 行进 (touch.position
)。要获得该射线上的特定点,您必须指定沿该射线的距离:d。当你设置d为0时,你得到的恰好是C,这不仅离相机太近了,实际上是在相机上。 d < near 适用,因此 touchPosition
处的任何对象都不会被渲染。
长话短说:确保 near < d < far,您将得到一个 touchPosition
,您可以在上面放置对象并渲染它们。
float d = Camera.main.nearClipPlane + 2f; // added some buffer to accommodate for object dimensions
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(
new Vector3(touch.position.x, touch.position.y, d));
我遇到了麻烦。我想简单地将我的游戏对象立即(无动画)移动到触摸的屏幕部分。我不希望对象是可拖动的。我只希望用户能够通过触摸屏幕上的区域来移动对象,而不是拖动。在我的代码中,它正在检测触摸,但只要我触摸屏幕上的某处,对象就会消失(在我的 iOS phone 上测试)。这是一个2D游戏。我不确定这是否会影响它,但对于我的游戏,相机总是向下移动。
这是在我的 Update() 函数中:
if(Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Touch touch = Input.GetTouch(0);
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 0));
transform.position = touchPosition;
}
我猜问题出在您将深度指定为 0。
让 C 成为您的相机。你的相机会观察 space 并渲染它能看到的所有物体,只要物体不是离得太远 (d > far) 并且不太近 (d < 附近)。 当你打电话给
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(
new Vector3(touch.position.x, touch.position.y, 0));
你基本上是说:我需要找到一个位于射线上的点,从 C (Camera.main
) 开始并向 M 行进 (touch.position
)。要获得该射线上的特定点,您必须指定沿该射线的距离:d。当你设置d为0时,你得到的恰好是C,这不仅离相机太近了,实际上是在相机上。 d < near 适用,因此 touchPosition
处的任何对象都不会被渲染。
长话短说:确保 near < d < far,您将得到一个 touchPosition
,您可以在上面放置对象并渲染它们。
float d = Camera.main.nearClipPlane + 2f; // added some buffer to accommodate for object dimensions
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(
new Vector3(touch.position.x, touch.position.y, d));