简体   繁体   English

libgdx-将精灵捕捉到光标

[英]libgdx - snap sprite to cursor

I am currently trying to snap a crosshair sprite to my game's cursor using libgdx. 我目前正在尝试使用libgdx将十字准线精灵捕捉到游戏光标上。 The game is top-down view: 游戏是自上而下的视图:

    Texture crosshair_text = new Texture(Gdx.files.internal("data/crosshair1.png"));
    this.crosshair = new Sprite(crosshair_text, 0, 0, 429, 569);

    //...
@Override
public void render() {  

    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    cam.update();
    batch.setProjectionMatrix(cam.combined);

    batch.begin();

    //.. sprites that scale based on camera (top-down view)

    batch.end();

    //draws 'ui' elements
    floatingBatch.begin();

    //...

    //snap to cursor
    this.crosshair.setPosition( Gdx.input.getX(), (Gdx.graphics.getHeight()-Gdx.input.getY()) );

    //transform
    this.crosshair.setScale(1/cam.zoom);

    //draw
    this.crosshair.draw(floatingBatch);

    floatingBatch.end();
}

Sorry if there are errors that I didn't catch, this isn't an exact copy of my code. 抱歉,如果我没有发现错误,这不是我的代码的精确副本。 The problem here is that 1. The sprite doesn't snap to the correct position and 2. the crosshair sprite lags behind the current position of the mouse on the screen. 这里的问题是:1.子画面无法捕捉到正确的位置,并且2.十字准线子画面滞后于屏幕上鼠标的当前位置。 Can anyone give me insight on how to fix either of these two issues? 谁能给我关于如何解决这两个问题的见解?

Your position might not be correct because the screen location isn't necessarily the right location to draw onto using your OrthographicCamera , try using the unproject first. 您的位置可能不正确,因为屏幕位置不一定是使用OrthographicCamera绘制的正确位置,请先尝试使用unproject Eg: 例如:

Vector3 mousePos = new Vector3( Gdx.input.getX(), (Gdx.graphics.getHeight()-Gdx.input.getY()), 0); //Get the mouse-x and y like in your code
cam.unproject(mousePos); //Unproject it to get the correct camera position
this.crosshair.setPosition(mousePos.x, mousePos.y); //Set the position

Plus you need to make sure your floating batch is set to the projection matrix of the camera, add the following code: 另外,您需要确保将浮动批处理设置为相机的投影矩阵,并添加以下代码:

floatingBatch.setProjectionMatrix(cam.combined);

Instead of drawing a Sprite at the mouse position, you could change the cursor image: 您可以更改光标图像,而不是在鼠标位置绘制Sprite

Gdx.input.setCursorImage(cursorPixMap, hotspotX, hotspotY);

Where cursorPixMap is a PixMap of the new cursor image an hotspotX and hotspotY is the "origin" of the PixMap /cursor image. 其中cursorPixMap是新光标图像的PixMap ,而hotspotXhotspotYPixMap / cursor图像的“原点”。 In your case it would be the center of the crosshair . 在您的情况下,它将是crosshair的中心。
So basicly the Gdx.input.getX() and Gdx.input.getY() return the current position of the hotspotX and hotspotY . 因此,基本上, Gdx.input.getX()Gdx.input.getY()返回hotspotXhotspotY的当前位置。

I suggest to read the wiki artikcle about the cursor . 我建议阅读有关光标的Wiki文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM