使用 ScreenPointToRay 滞后的对象跟随鼠标
Object following mouse using ScreenPointToRay lagging
我正在构建一个 3d topdown 射击游戏。玩家用键盘控制头像,用鼠标控制十字线。
我根据这篇文章找到了一个简单的方法来实现标线:
https://gamedevbeginner.com/how-to-convert-the-mouse-position-to-world-space-in-unity-2d-3d/
我定义了一个代表标线的对象并附加了这个脚本:
public class Reticule : MonoBehaviour
{
Camera mainCamera;
Plane plane;
float distance;
Ray ray;
// Start is called before the first frame update
void Start()
{
mainCamera = Camera.main;
plane = new Plane(Vector3.up, 0);
// This would be turned off in the game. I set to on here, to allow me to see the cursor
Cursor.visible = true;
}
// Update is called once per frame
void Update()
{
ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out distance))
{
transform.position = ray.GetPoint(distance);
}
}
}
这行得通,但问题是十字线滞后于鼠标光标,当我停止移动鼠标时会追上。
这是因为这种方法很慢吗?是否有另一种简单的方法可以达到同样的效果?
the issue is that the reticule is lagging behind the mouse cursor, and catches up when I stop moving the mouse
这很正常,图形驱动程序(在 WDM 的帮助下)绘制鼠标光标的速度与鼠标数据信息通过线路传输的速度一样快,而您的游戏仅以固定帧速率(或更慢)呈现。您的硬件鼠标将始终领先于您的游戏绘制它的位置或与之相关的任何内容。
一些可以帮助解决这个问题的事情:
不要显示系统光标,而是显示您自己的光标。这样,您显示的光标将始终位于您的游戏认为的相同位置(因为它绘制了它)并且您不会遇到这个问题。但是要小心,因为如果你的游戏帧率开始下降,当你的光标移动不再流畅时,它会非常明显。
不要将对象绑定到光标上。该问题不会通过正常交互显示,例如单击按钮。在 RTS 游戏中围绕单位绘制框时,您会注意到这一点,但我很难想到另一个这样的例子。
像上面一样,但限制较少,您可以将绑定到光标的对象插入到位,因此它们总是有意地在它后面。它使它看起来更具游戏性,这对于您知道的游戏来说并不是那么糟糕。当然,我不会为紧张的射手这样做。
我正在构建一个 3d topdown 射击游戏。玩家用键盘控制头像,用鼠标控制十字线。
我根据这篇文章找到了一个简单的方法来实现标线: https://gamedevbeginner.com/how-to-convert-the-mouse-position-to-world-space-in-unity-2d-3d/
我定义了一个代表标线的对象并附加了这个脚本:
public class Reticule : MonoBehaviour
{
Camera mainCamera;
Plane plane;
float distance;
Ray ray;
// Start is called before the first frame update
void Start()
{
mainCamera = Camera.main;
plane = new Plane(Vector3.up, 0);
// This would be turned off in the game. I set to on here, to allow me to see the cursor
Cursor.visible = true;
}
// Update is called once per frame
void Update()
{
ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out distance))
{
transform.position = ray.GetPoint(distance);
}
}
}
这行得通,但问题是十字线滞后于鼠标光标,当我停止移动鼠标时会追上。 这是因为这种方法很慢吗?是否有另一种简单的方法可以达到同样的效果?
the issue is that the reticule is lagging behind the mouse cursor, and catches up when I stop moving the mouse
这很正常,图形驱动程序(在 WDM 的帮助下)绘制鼠标光标的速度与鼠标数据信息通过线路传输的速度一样快,而您的游戏仅以固定帧速率(或更慢)呈现。您的硬件鼠标将始终领先于您的游戏绘制它的位置或与之相关的任何内容。
一些可以帮助解决这个问题的事情:
不要显示系统光标,而是显示您自己的光标。这样,您显示的光标将始终位于您的游戏认为的相同位置(因为它绘制了它)并且您不会遇到这个问题。但是要小心,因为如果你的游戏帧率开始下降,当你的光标移动不再流畅时,它会非常明显。
不要将对象绑定到光标上。该问题不会通过正常交互显示,例如单击按钮。在 RTS 游戏中围绕单位绘制框时,您会注意到这一点,但我很难想到另一个这样的例子。
像上面一样,但限制较少,您可以将绑定到光标的对象插入到位,因此它们总是有意地在它后面。它使它看起来更具游戏性,这对于您知道的游戏来说并不是那么糟糕。当然,我不会为紧张的射手这样做。