简体   繁体   中英

How do I attach the coordinates of a sprite to its center? LibGDX

I want that when I set a sprite to certain coordinates, it is set to these coordinates by its center.

为了清楚起见,我画了图片

You can use Sprite.setCenter(x,y)

Sets the position so that the sprite is centered on (x, y)

There's no Sprite.getCenterX() or Sprite.getCenterY() tho. If you need this you can create a class that extends Sprite and implement it your self...

public class MySprite extends Sprite {
    public MySprite(Texture texture) {
        super(texture);
    }

    public float getCenterX(){
        return getX()+getWidth()/2;
    }

    public float getCenterY(){
        return getY()+getHeight()/2;
    }
}

And now use MySprite .

You could also override all position related methods

public class MySprite extends Sprite {
    public MySprite(Texture texture) {
        super(texture);
    }

    @Override
    public void setX(float x) {
        super.setX(x-getWidth()/2);
    }

    @Override
    public void setY(float y) {
        super.setY(y-getHeight()/2);
    }

    @Override
    public void setPosition(float x, float y) {
        super.setPosition(x-getWidth()/2, y-getHeight()/2);
    }

    @Override
    public float getX() {
        return super.getX()+getWidth()/2;
    }

    @Override
    public float getY() {
        return super.getY()+getHeight()/2;
    }
}

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