简体   繁体   中英

libgdx - snap sprite to cursor

I am currently trying to snap a crosshair sprite to my game's cursor using 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. 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. 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:

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. In your case it would be the center of the crosshair .
So basicly the Gdx.input.getX() and Gdx.input.getY() return the current position of the hotspotX and hotspotY .

I suggest to read the wiki artikcle about the cursor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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