我正在J2ME上工作,我的游戏循环做以下事情:
public void run() {
Graphics g = this.getGraphics();
while (running) {
long diff = System.currentTimeMillis() - lastLoop;
lastLoop = System.currentTimeMillis();
input();
this.level.doLogic();
render(g, diff);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
stop(e);
}
}
}
这只是一个基本的游戏循环,doLogic()
函数调用场景中所有角色的逻辑函数,render(g, diff)
调用场景中每个角色的 animateChar
函数。接下来,在 Character 类中的 animChar
函数将屏幕设置为如下:
protected void animChar(long diff) {
this.checkGravity();
this.move((int) ((diff * this.dx) / 1000), (int) ((diff * this.dy) / 1000));
if (this.acumFrame > this.framerate) {
this.nextFrame();
this.acumFrame = 0;
} else {
this.acumFrame += diff;
}
}
这确保了所有的事情都必须按照机器从一个周期到另一个周期所需的时间来进行(请记住这是一台手机,而不是游戏电脑)。我相信这不是实现此行为的最有效方法,因此我完全接受在评论中对我的编程技能提出批评,但这是我的问题:当我让角色跳跃时,我所做的就是将他的dy设置为负值,例如-200,并将布尔值jumping设置为true,这会使角色向上移动,然后我有这个名为
checkGravity()
的函数,它确保所有上升的东西都必须下降,checkGravity
还检查角色是否在平台上,所以我会简化它,以节省您的时间:public void checkGravity() {
if (this.jumping) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 0) {
this.jumping = false;
this.falling = true;
}
this.dy = this.jumpSpeed;
}
if (this.falling) {
this.jumpSpeed += 10;
if (this.jumpSpeed > 200) this.jumpSpeed = 200;
this.dy = this.jumpSpeed;
if (this.collidesWithPlatform()) {
this.falling = false;
this.standing = true;
this.jumping = false;
this.jumpSpeed = 0;
this.dy = this.jumpSpeed;
}
}
}
问题在于,这个函数会更新dy,无论diff如何,导致在慢速机器上角色像超人一样飞行,而我不知道如何实现diff因素,使得当角色跳跃时,他的速度按比例随着游戏速度减少。有人能帮我解决这个问题吗?或者给我指点如何以正确的方式在J2ME中进行2D跳跃。