在Scene2D中移动精灵

时间:2015-02-17 19:06:18

标签: java scene2d

我目前正在尝试使用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() {
    }
}

1 个答案:

答案 0 :(得分:0)

在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