Get cursor position in LIBGDX

末鹿安然 提交于 2019-12-04 09:22:07

问题


How to get cursor position in libgdx and apply it to sprite? Like this?

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.


回答1:


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 values regardless of button state.)

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

  • touchMoved callback (on older libGDX versions)
  • mouseMoved callback (on newer libGDX versions)

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

Apply position to sprite

Update a Vector2 that 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.

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.)




回答2:


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.



来源:https://stackoverflow.com/questions/16381031/get-cursor-position-in-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!