首页 > 解决方案 > Libgdx 演员 moveTo 动作不起作用

问题描述

我试图通过动作从一个点到另一个点移动舞台上的演员,但它不起作用,我已经尝试了几个小时,它只是不起作用,我会很高兴得到帮助..

我已经在互联网上搜索了代码,但我尝试的所有方法都没有奏效,我真的不明白这段代码有什么问题,它与互联网教程中的工作基本相同

演员类:

public class Player extends Actor {

float x,y;
float screenWidth,screenHeight;
private Sprite sprite;
Texture image;
float width,height;
public Player(Texture image,float x, float  y,float width,float height, float screenWidth, float screenHeight)
{
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    this.screenWidth = screenWidth;
    this.screenHeight = screenHeight;

    this.image = image;
    sprite = new Sprite(image, 0, 0, image.getWidth(), image.getHeight());
    sprite.setPosition(x, y);

}

@Override
public float getX() {
    return x;
}

@Override
public void setX(float x) {
    this.x = x;
}

@Override
public float getY() {
    return y;
}

@Override
public void setY(float y) {
    this.y = y;
}

@Override
public float getWidth() {
    return width;
}

@Override
public void setWidth(float width) {
    this.width = width;
}

@Override
public float getHeight() {
    return height;
}

@Override
public void setHeight(float height) {
    this.height = height;
}

@Override
public void act(float delta) {
    super.act(delta);
}

@Override
public void draw (Batch batch, float parentAlpha) {
    batch.draw(sprite,x,y,width,height);
}
}

和主要课程:

            player = new Player(playerTexture,screenWidth/2,screenHeight-200,playerTexture.getWidth(),playerTexture.getHeight(),screenWidth,screenHeight);
 MoveToAction action = new MoveToAction();
        action.setPosition(300f,0f);
        action.setDuration(10f);
        player.addAction(action);

  @Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.setProjectionMatrix(orthographicCamera.combined);
    batch.begin();
    // batch.draw(playerTexture,10,10,10,10);

    batch.end();

    stage.act(Gdx.graphics.getDeltaTime());

    stage.draw(); //this will call the batch to draw the sprite
}

标签: javaandroidlibgdxactor

解决方案


Actor 已经具有 x、y、宽度和高度字段。由于您创建了自己的参数,因此您已经隐藏了这些参数。

您的问题的根源是您未能覆盖setPosition()使用您的字段。因此,移动操作调用它并更改您隐藏的字段,当您绘制它时,您正在使用自己的未更改的字段。

不要隐藏字段。它非常容易出错。您应该删除我上面提到的字段,以及您对 getter 和 setter 的所有覆盖。

以下是一般的 OOP 经验法则:如果您在不调用 super 方法的情况下覆盖任何 getter 或 setter,那么您可能会破坏某些东西。

不相关,但您应该使用 TextureRegion 而不是 Sprite。Sprite 是一个 TextureRegion,带有额外的大小和位置参数。由于这些功能也在 Actor 中,因此使用 Sprite 是多余且容易出错的。


推荐阅读