我目前正在制作一款游戏,你驾驶坦克,我正在玩玩家类。我希望坦克具有惯性,可以进行一些逼真的运动。我有这个问题,我的坦克的速度没有达到我设定的极限。奇怪的是角速度部分尽我所知是有效的。两个块都使用相同的逻辑。现在坦克速度最大值从1.6开始,然后在2到3之间,然后是5和6,每次你向前/向后点击。
以下是代码:
final class Player extends GameObject {
private static final double ANGLE_VELOCITY_MAX = Math.PI / 60, ANGLE_VELOCITY_STEP = Math.PI / 900,
ACCELERATION_STEP = .1, ACCELERATION_MAX = 1;
private double angle = 0, angleVelocity = 0, speed = 0, acceleration = 0;
@Override
public final void tick() {
if (gc.getKey(KeyEvent.VK_W) && speed < ACCELERATION_MAX)
if (acceleration + ACCELERATION_STEP > ACCELERATION_MAX)
acceleration = ACCELERATION_MAX;
else
acceleration += ACCELERATION_STEP;
else if (gc.getKey(KeyEvent.VK_S) && speed > -ACCELERATION_MAX)
if (acceleration - ACCELERATION_STEP < -ACCELERATION_MAX)
acceleration = -ACCELERATION_MAX;
else
acceleration -= ACCELERATION_STEP;
else if (Math.abs(acceleration) < ACCELERATION_STEP)
acceleration = 0;
else
acceleration -= Math.signum(acceleration) * ACCELERATION_STEP;
if (gc.getKey(KeyEvent.VK_D) && angleVelocity < ANGLE_VELOCITY_MAX)
if (angleVelocity + ANGLE_VELOCITY_STEP > ANGLE_VELOCITY_MAX)
angleVelocity = ANGLE_VELOCITY_MAX;
else
angleVelocity += ANGLE_VELOCITY_STEP;
else if (gc.getKey(KeyEvent.VK_A) && angleVelocity > -ANGLE_VELOCITY_MAX)
if (angleVelocity - ANGLE_VELOCITY_STEP < -ANGLE_VELOCITY_MAX)
angleVelocity = -ANGLE_VELOCITY_MAX;
else
angleVelocity -= ANGLE_VELOCITY_STEP;
else if (Math.abs(angleVelocity) < ANGLE_VELOCITY_STEP)
angleVelocity = 0;
else
angleVelocity -= Math.signum(angleVelocity) * ANGLE_VELOCITY_STEP;
if (--treadCooldown <= 0) {
if (++treadIndex >= treads.length)
treadIndex = 0;
treadCooldown = TREAD_COOLDOWN;
}
angle += angleVelocity;
speed += acceleration;
location.translate(Math.cos(angle) * speed, Math.sin(angle) * speed);
}
答案 0 :(得分:1)
我的猜测是你应该speed
独立于ACCELERATION_MAX
引入一些限制,将第一个if
编辑为:
if (gc.getKey(KeyEvent.VK_W) && acceleration < ACCELERATION_MAX)
...
else if (gc.getKey(KeyEvent.VK_S) && acceleration > -ACCELERATION_MAX)
...
并在最后确保speed
在可接受的范围内。
顺便说一句:
我必须承认上面的代码对我来说真的很难阅读(更不用说理由了) - 我建议重组一下:
@Override
public final void tick() {
if (gc.getKey(KeyEvent.VK_W)) accelerate(ACCELERATION_STEP);
else if (gc.getKey(KeyEvent.VK_S)) accelerate(-ACCELERATION_STEP);
else accelerate(- Math.signum(acceleration) * ACCELERATION_STEP);
// etc.. you get the idea
}
private void accelerate(double delta) {
setAcceleration(acceleration +delta);
}
private void setAcceleration(double value) {
acceleration = roundToZero(constrain(value, -ACCELERATION_MAX, ACCELERATION_MAX), ACCELERATION_STEP);
}
private static double constrain(double value, double min, double max) {
return value > max ? max : (value < min ? min : value);
}
private static double roundToZero(double value, double radius) {
return Math.abs(value) < radius ? 0 : value;
}
免责声明:没有测试上述内容,也没有尝试编译它。