我现在正在使用libGDX / Box2D,我完全被我在遵循这套教程libGDX时发现的错误所困扰。
在我的游戏中,我创建了一个演员并将其添加到我的游戏阶段。演员以给定的y坐标放置在屏幕上。游戏只是循环播放动画以模拟跑步。
问题是,当我将演员放在游戏舞台上时,y坐标会以某种方式给出错误的y坐标,使用以下代码片段进行检索。
body.getPosition().y
在游戏启动时,actor的y坐标从2.5的正确位置变为3.6的错误位置。然后,演员从其更新(不正确)的y位置开始正常运作。
我已经调试了我的代码的bejaysus,我看不到任何会导致这种情况的东西。以前有没有人遇到过这种行为?这是我不知道的某种Box2D细微差别吗?
游戏演员类
public abstract class GameActor extends Actor {
protected Body body;
protected UserData userData;
protected Rectangle screenRectangle;
public GameActor() {
}
public GameActor(Body body) {
this.body = body;
this.userData = (UserData) body.getUserData();
screenRectangle = new Rectangle();
}
@Override
public void act(float delta) {
super.act(delta);
if (body.getUserData() != null) {
updateRectangle();
} else {
// This means the world destroyed the body (enemy or runner went out of bounds)
remove();
}
}
public abstract UserData getUserData();
private void updateRectangle() {
screenRectangle.x = transformToScreen(body.getPosition().x - userData.getWidth() / 2);
screenRectangle.y = transformToScreen(body.getPosition().y - userData.getHeight() / 2);
screenRectangle.width = transformToScreen(userData.getWidth());
screenRectangle.height = transformToScreen(userData.getHeight());
}
protected float transformToScreen(float n) {
return Constants.WORLD_TO_SCREEN * n;
}
}
亚军类
public class Runner extends GameActor {
...
@Override
public void draw(Batch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
float x = screenRectangle.x - (screenRectangle.width * 0.1f);
float y = screenRectangle.y;
float width = screenRectangle.width * 1.5f;
stateTime += Gdx.graphics.getRawDeltaTime();
batch.draw(runningAnimation.getKeyFrame(stateTime, true), x, y - 40, width, screenRectangle.height);
}
}
}