【发布时间】:2019-10-03 22:00:18
【问题描述】:
我有一个游戏,它有一个船对象(带有 JavaFX 多边形)。当我用我的键(通过 EventHandlers 和 AnimationTimers)移动飞船时,它会向上移动。当我放手时,它应该将加速度变为-4,因此它不断从船的速度中带走-4,直到它假设达到0。但是,因为船可以向各个方向移动,所以速度有时是负的当船前进时。因此,当我试图在速度为负时停止船时,它不会发生,船一直向后移动。
当船的速度为负并向前移动时,我尝试了一些计算,但它有点太复杂了,我相信它不起作用。
这里是 Ship 计算速度 x 方法的代码:
AnimationTimer calculateVelocityX = new AnimationTimer() {
@Override
public void handle(long now) {
if (getAcceleration() == 17)
setVelocityX(getVelocityX() + (Math.cos(Math.toRadians(getRotation())) * (getAcceleration() * 0.01)));
else if (acceleration == -4)
setVelocityX(getVelocityX() + (Math.cos(Math.toRadians(getTempRotation())) * (getAcceleration() * 0.01)));
}
};
AnimationTimer shipAccelerationTimer = new AnimationTimer() {
@Override
public void handle(long now) {
getShipImage().setLayoutX(getShipImage().getLayoutX() + getVelocityX());
getShipImage().setLayoutY(getShipImage().getLayoutY() - getVelocityY());
wrapShip();
if (getVelocityX() == 0 && getVelocityY() == 0) {
getCalculateVelocityX().stop();
getCalculateVelocityY().stop();
setAcceleration(17);
setCounterOne(0);
setCounterTwo(0);
setCounterThree(0);
getShipAccelerationTimer().stop();
}
}
};
此代码将使船向后移动,因为由于小数精度,速度实际上永远不会达到 0。但是,如果我说当速度小于 0 时,根据我上面所说的,这是不可能的。
货物沿指定方向移动时的速度标志图:
https://i.stack.imgur.com/5sxNi.png
因此,我不能只拥有“当速度小于 0 时”,因为就像在象限 2、3、4 中一样,我可以向前移动,但具有负 x、y 速度或两者兼而有之。
【问题讨论】:
-
可以考虑使用
<= 0?和/或将值四舍五入为Int -
@kleopatra 我不喜欢泄露我的代码。对不起。希望我提供的代码就足够了。
-
@MadProgrammer
-
对不起,我的意思是我不喜欢把我所有的代码都泄露出去,你说得对。如果我没有提供太多代码,我可以回答如何解决它。如果有的话,最好有代码解决方案。
-
请查看代表速度符号的图像的新编辑。