Search code examples
javalibgdx

Getting coordinates of mouse and sprite on Libgdx


I want to scale my sprite when I hover the mouse above it, but I can't find a way to do it. Maybe it is a problem with my drawing using the same sprite?

Here is my code:

Texture t = new Texture("sprite.png");
Sprite s = new Sprite(t);
Spritebatch batch = new Spritebatch();


batch.begin()
positionX=(1366)/4 * 3;
positionY =525;

for(int i=0;i<3;i++){
   for (int i=0;i<3;i++){

        batch.draw(s,positionX-50,positionY-160,125,125);

        positionY-=110;
    }

batch.end();

There's three sprites drawed on that for loop, I want to scale only the sprite where I hover my mouse.


Solution

  • You can scale your sprite by using s.setSize(scale * s.getWidth(), scale * s.getHeight())

    I would not recommend using batch.draw for a sprite.

    I would use s.setPosition(x, y) and then s.draw(batch) which uses the sprite's set position and size

    You can find out if your mouse is over the sprite with the following

    if(Gdx.input.getX() > s.getX() && Gdx.input.getX() < s.getX + s.getWidth() &&
       Gdx.input.getY() > s.getY() && Gdx.input.getY() < s.getY + s.getHeight())
    

    And call resizing code from there