java - 如何将 Sprite 的坐标附加到其中心? LibGDX

标签 java libgdx sprite

我希望当我将 Sprite 设置为某些坐标时,它会通过其中心设置为这些坐标。

For clarity I drew the picture

最佳答案

您可以使用Sprite.setCenter(x,y)

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

但是没有 Sprite.getCenterX()Sprite.getCenterY() 。如果您需要这个,您可以创建一个扩展 Sprite 的类并自行实现...

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;
    }
}

现在使用MySprite

您还可以覆盖所有与位置相关的方法

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;
    }
}

关于java - 如何将 Sprite 的坐标附加到其中心? LibGDX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61258928/

相关文章:

javascript - 如何与 LibGDX HTML5 应用程序通信?

java - Libgdx JsonWriter StackOverflowError 错误

java - Android - 可以多次注册接收器吗?

java - libGDX新手困惑

c++ - 使用 OpenGL 的 2D Sprite 动画技术

java - 使用java仅显示图像的一部分

ios - cocos2d sprite 永远重复动画

java - if(null check)-else vs try catch(NullPointerException) 哪个效率更高?

java - Maven编译时找不到sun.jvm.hotspot

java - 返回图像资源 ID