Java 获取 LIBGDX 中的光标位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16381031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:35:28  来源:igfitidea点击:

Get cursor position in LIBGDX

javalibgdx

提问by CodeAndWave

How to get cursor position in libgdx and apply it to sprite? Like this? enter image description here

如何在libgdx中获取光标位置并将其应用于精灵?像这样? 在此处输入图片说明

I want my sprite to have the direction pointed wherever my cursor is in the screen.I search libgdx examples but i cant find any examples related to that.

我希望我的精灵在我的光标在屏幕上的任何地方都有指向的方向。我搜索 libgdx 示例,但我找不到任何与此相关的示例。

采纳答案by P.T.

Get cursor position

获取光标位置

If you're polling for input, use Gdx.input.getX()and Gdx.input.getY()to get the current mouse x and y coordinates. (The doc says its only relevant for touch, but the code looks like it reports raw mouse valuesregardless of button state.)

如果您要轮询输入,请使用Gdx.input.getX()Gdx.input.getY()获取当前鼠标的 x 和 y 坐标。(文档说它只与触摸相关,但代码看起来像无论按钮状态如何都报告原始鼠标值。)

If you're using an InputProcessoryou can use one of:

如果您使用的是InputProcessor,则可以使用以下之一:

to receive input events from a mouse with no buttons pressed.

从鼠标接收输入事件而不按下任何按钮。

Apply position to sprite

将位置应用到精灵

Update a Vector2that points from the current sprite position to the cursor position. This can be your Sprite's heading. You'll want to rotate the sprite's heading to match this vector.

更新Vector2从当前精灵位置指向光标位置的 a。这可以是您的 Sprite 的标题。您需要旋转精灵的标题以匹配此向量。

Use Vector2.angle()to compute the angle of this vector, and set your sprite's rotation to this. (This is relative to the positive X axis,so you may need to add a constant if you want it relative to the Y axis.)

使用Vector2.angle()来计算这个矢量的角度,和你的精灵的旋转集合了这一点。(这是相对于正 X 轴的,因此如果您希望它相对于 Y 轴,则可能需要添加一个常量。)

回答by francogp

I usually track my mouse into world coordinates like this:

我通常将鼠标跟踪到世界坐标中,如下所示:

    // variables
    private final Vector2 mouseInWorld2D = new Vector2();
    private final Vector3 mouseInWorld3D = new Vector3();
    private final OrthographicCamera cam; 
    .
    .
    .
    //in render() code
    mouseInWorld3D.x = Gdx.input.getX();
    mouseInWorld3D.y = Gdx.input.getY();
    mouseInWorld3D.z = 0;
    cam.unproject(mouseInWorld3D);
    mouseInWorld2D.x = mouseInWorld3D.x;
    mouseInWorld2D.y = mouseInWorld3D.y;

Then, I can use mouseInWorld2D to access mouse coordinates (relative to the scene/world) in my game. A sprite can track that coordinate very easy and compute its angle and direction.

然后,我可以使用 mouseInWorld2D 访问游戏中的鼠标坐标(相对于场景/世界)。精灵可以非常轻松地跟踪该坐标并计算其角度和方向。