基于带有滑动手势的对象方向的光线投射
Raycast based on object direction with swipe gestures
在我的游戏中,当玩家在 4 个方向中的任何一个方向滑动时,都会根据该方向从对象创建一条射线,然后该对象会朝该方向旋转:
void Update ()
{
if (direction == SwipeDirection.Up)
{
RayTest (transform.forward)
transform.rotation = Quaternion.LookRotation (Vector3.forward);
}
if (direction == SwipeDirection.Right)
{
RayTest (transform.right)
transform.rotation = Quaternion.LookRotation (Vector3.right);
}
if (direction == SwipeDirection.Down)
{
RayTest (-transform.forward)
transform.rotation = Quaternion.LookRotation (Vector3.back);
}
if (direction == SwipeDirection.Left)
{
RayTest (-transform.right)
transform.rotation = Quaternion.LookRotation (Vector3.left);
}
}
void RayTest (Vector3 t)
{
// "transform.position + Vector3.up" because the pivot point is at the bottom
// Ray is rotated -45 degrees
Ray ray = new Ray(transform.position + Vector3.up , (t - transform.up).normalized);
Debug.DrawRay (ray.origin, ray.direction, Color.green, 1);
}
如果我在每次滑动后不旋转对象,代码会完美运行,旋转它会弄乱方向,所以如果玩家向上滑动并且对象向右看,光线方向就会变成它的前向这是对的。
我该如何解决这个问题?
您通过说 transform.right
来指定相对于变换的光线方向。这意味着一旦你旋转了你的变换,transform.right
的意义就与之前不同了。
您没有指定相机是否随播放器旋转,所以我假设它不会。在此假设下,SwipeDirection.Right
始终表示相同的方向,因此 RayTest(..)
也应始终测试相同的方向。
所以我想你只需要像 Vector3.right
这样的恒定方向作为 RayTest(..)
的参数。
在我的游戏中,当玩家在 4 个方向中的任何一个方向滑动时,都会根据该方向从对象创建一条射线,然后该对象会朝该方向旋转:
void Update ()
{
if (direction == SwipeDirection.Up)
{
RayTest (transform.forward)
transform.rotation = Quaternion.LookRotation (Vector3.forward);
}
if (direction == SwipeDirection.Right)
{
RayTest (transform.right)
transform.rotation = Quaternion.LookRotation (Vector3.right);
}
if (direction == SwipeDirection.Down)
{
RayTest (-transform.forward)
transform.rotation = Quaternion.LookRotation (Vector3.back);
}
if (direction == SwipeDirection.Left)
{
RayTest (-transform.right)
transform.rotation = Quaternion.LookRotation (Vector3.left);
}
}
void RayTest (Vector3 t)
{
// "transform.position + Vector3.up" because the pivot point is at the bottom
// Ray is rotated -45 degrees
Ray ray = new Ray(transform.position + Vector3.up , (t - transform.up).normalized);
Debug.DrawRay (ray.origin, ray.direction, Color.green, 1);
}
如果我在每次滑动后不旋转对象,代码会完美运行,旋转它会弄乱方向,所以如果玩家向上滑动并且对象向右看,光线方向就会变成它的前向这是对的。
我该如何解决这个问题?
您通过说 transform.right
来指定相对于变换的光线方向。这意味着一旦你旋转了你的变换,transform.right
的意义就与之前不同了。
您没有指定相机是否随播放器旋转,所以我假设它不会。在此假设下,SwipeDirection.Right
始终表示相同的方向,因此 RayTest(..)
也应始终测试相同的方向。
所以我想你只需要像 Vector3.right
这样的恒定方向作为 RayTest(..)
的参数。