简体   繁体   中英

Moving sprites in Scene2D

I am currently trying to build a simple game using Scene2D - I have looked for and tried some ways to move my sprite around the screen using the Arrow keys, but I have not had any luck. How can I make the sprite move according to the Key Events?

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() {
    }
}

Well in Libgdx handling keys is really easy. You can simply use the method Gdx.input.isKeyPressed(intRepresentingTheKey);

So you could do something like this:

// ** 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);

This is a very simple solution for your problem. When you want to get more serious about key events and other events you should take a look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM