【问题标题】:Java game with libGDX: my ship cant move to the right使用 libGDX 的 Java 游戏:我的船不能向右移动
【发布时间】:2022-11-25 07:48:03
【问题描述】:

我正在做一个 Java 项目,其中包括制作“太空入侵者”克隆。我从船舶运动开始,在 stackOverflow 上搜索我发现了这段代码:

if(Gdx.input.isKeyPressed(Input.Keys.LEFT) )
    x -= Gdx.graphics.getDeltaTime() * PlayerSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) )
    x += Gdx.graphics.getDeltaTime() * PlayerSpeed;

我将它用于 playerShip(下面的类):

public class PlayerShip extends Ship {
    private Animator animator;
    private float PlayerSpeed = 20.0f;
    private int x,y;

    public PlayerShip(SpriteBatch batch){
        this.animator=new Animator(batch,"ship.png", 5, 2);
    }

    public void create(){
        animator.create();
    }

    public void render(){
        this.animator.render(this.x,this.y);
        if(Gdx.input.isKeyPressed(Input.Keys.LEFT) )
            x -= Gdx.graphics.getDeltaTime() * PlayerSpeed;
        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) )
            x += Gdx.graphics.getDeltaTime() * PlayerSpeed;
    }



    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }
}

游戏(主要):

public class Game extends ApplicationAdapter {
    private SpriteBatch batch;

    private BackgroundManagement backgroundManagement;
    private BitmapFont font;

    private PlayerShip player;
    private SmallShip smallShip;


    @Override
    public void create() {
        Gdx.graphics.setWindowedMode(600, 800);
        batch = new SpriteBatch();
        player = new PlayerShip(batch);
        smallShip = new SmallShip(batch);
        player.create();
        player.setX(300);
        player.setY(100);
        smallShip.create();
        smallShip.setX(200);
        smallShip.setY(400);
        font = new BitmapFont(Gdx.files.internal("gamefont.fnt"),
                Gdx.files.internal("gamefont.png"), false);
        backgroundManagement = new BackgroundManagement(batch);
    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0.2f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.begin();
        backgroundManagement.render();
        player.render();
        smallShip.render();
        batch.end();
    }

    @Override
    public void dispose() {
        batch.dispose();
    }
}

尝试我的代码时,船没有向右移动,我尝试了各种解决方案,但没有找到任何解决方案,感谢任何帮助,谢谢!

【问题讨论】:

  • 无论如何,根据documentation,我认为您的代码没有任何问题。你可以向左移动而不是向右移动吗?

标签: java libgdx


【解决方案1】:

船的位置是一个整数。你的增量是一个浮点数。你可能有一个像样的显卡,可以在例如200+ fps 连续渲染(甚至更疯狂)。在 200fps 的情况下,增量为 (1/200)*20 = 1/10 float。

integer += .1f 不会改变原来的整数。

将您的位置也更改为浮点数,然后在需要实际渲染时将其转换(或转换)为整数,以便 x 可以增加非常小的值。 也尝试浮动位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多