gpt4 book ai didi

java - 在 Scene2D 中移动 Sprite

转载 作者:太空宇宙 更新时间:2023-11-04 14:08:54 25 4
gpt4 key购买 nike

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

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

最佳答案

在 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 .

关于java - 在 Scene2D 中移动 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com