【问题标题】:Moving sprites in Scene2D在 Scene2D 中移动精灵
【发布时间】:2015-02-17 19:06:17
【问题描述】:

我目前正在尝试使用 Scene2D 构建一个简单的游戏 - 我已经寻找并尝试了一些方法来使用箭头键在屏幕上移动我的精灵,但我没有任何运气。如何让精灵根据关键事件移动?

public class MyGdxGame implements ApplicationListener {

public class MyActor extends Actor {
    Texture texture = new Texture(Gdx.files.internal("Sample.png"));
    public boolean started = false;

    public MyActor(){
        setBounds(getX(),getY(),texture.getWidth(),texture.getHeight());
    }

    @Override
    public void draw(Batch batch, float alpha){
        batch.draw(texture,this.getX(),getY());
    }
}
private Stage stage;

@Override
public void create() {        
    stage = new Stage();
    Gdx.input.setInputProcessor(stage);

    MyActor myActor = new MyActor();

    MoveToAction moveAction = new MoveToAction();
    moveAction.setPosition(300f, 0f);
    moveAction.setDuration(10f);
    myActor.addAction(moveAction);

    stage.addActor(myActor);
}

@Override
public void dispose() {
}

@Override
public void render() {    
    Gdx.gl.glClearColor(1/255f, 200/255f, 1/255f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stage.act(Gdx.graphics.getDeltaTime());
    stage.draw();
}

@Override
public void resize(int width, int height) {
}

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }
}

【问题讨论】:

  • 我不知道您正在使用的库,但您可能想尝试构建一个小型(非游戏)程序来试验获取事件并对其采取行动。

标签: java scene2d


【解决方案1】:

在 Libgdx 中处理密钥真的很容易。您可以简单地使用方法 Gdx.input.isKeyPressed(intRepresentingTheKey);

所以你可以这样做:

// ** Declare those 2 variables outside of the *render* method.
    int xDelta = 0;
    int yDelta = 0;


    // ** Make sure to put this in the render method **
    if(Gdx.input.isKeyPressed(Keys.RIGHT)) {
        xDelta = 20;
    }else if(Gdx.input.isKeyPressed(Keys.LEFT)) {
        xDelta = -20;
    }else if(Gdx.input.isKeyPressed(Keys.DOWN)) {
        yDelta = -20;
    }else if(Gdx.input.isKeyPressed(Keys.UP)) {
        yDelta = 20;
    }else if(Gdx.input.isKeyPressed(Keys.K)) {
        //This will make the actor stop moving when the "K" key is pressed.
        xDelta = 0; yDelta = 0;
    }

    //Move the Actor simply by using the moveBy(x,y); method.
    myActor.moveBy(xDelta, yDelta);

对于您的问题,这是一个非常简单的解决方案。当您想更认真地对待关键事件和其他事件时,您应该查看here

【讨论】:

    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 2023-03-15
    • 2015-05-20
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    相关资源
    最近更新 更多