我最近开始使用JavaFX而且我正在玩一个由WASD键控制的玩家的小游戏。起初我做到了这样你可以通过调整他的x&在keyPress的y坐标,但我发现运动非常粗糙。现在我换了东西,开始使用时间轴开始&按下并释放按键时停止它们。
代码:
Timeline timelineW = new Timeline();
Timeline timelineA = new Timeline();
Timeline timelineS = new Timeline();
Timeline timelineD = new Timeline();
public void createTimeLineW() {
timelineW.setCycleCount(Timeline.INDEFINITE);
final KeyValue kv = new KeyValue(player.yProperty(), -Integer.MAX_VALUE);
final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
timelineW.getKeyFrames().add(kf);
}
public void createTimeLineA() {
timelineA.setCycleCount(Timeline.INDEFINITE);
final KeyValue kv = new KeyValue(player.xProperty(), -Integer.MAX_VALUE);
final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
timelineA.getKeyFrames().add(kf);
}
public void createTimeLineS() {
timelineS.setCycleCount(Timeline.INDEFINITE);
final KeyValue kv = new KeyValue(player.yProperty(), Integer.MAX_VALUE);
final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
timelineS.getKeyFrames().add(kf);
}
public void createTimeLineD() {
timelineD.setCycleCount(Timeline.INDEFINITE);
final KeyValue kv = new KeyValue(player.xProperty(), Integer.MAX_VALUE);
final KeyFrame kf = new KeyFrame(Duration.hours(3000), kv);
timelineD.getKeyFrames().add(kf);
}
这是当前运动的基础。因此,在按下W时,imageView播放器将获得timelineW.play(),并且在释放W时它将获得timelineW.stop();和其他键一样。我做出这一改变的总体原因是因为运动更加平稳,但仍然存在一些错误。有可能甚至做这个运动吗?或者我应该考虑替代方案。
感谢正手。
答案 0 :(得分:0)
通常,您需要定期检查密钥并重置移动时间轴:
/** Distance player moves in one "step." */
private static final int movementDistance = 10;
/** Time it takes to move one "step." */
private static final Duration movementTime = Duration.seconds(0.5);
private Timeline xMovement;
private void checkMovementKeys() {
// ...
if (xMovement == null) {
xMovement = new Timeline();
}
if (rightMovementKeyPressed) {
xMovement.getKeyFrames().setAll(
new KeyFrame(movementTime,
new KeyValue(player.xProperty(),
player.getX() + movementDistance)));
xMovement.playFromStart();
}
if (leftMovementKeyPressed) {
xMovement.getKeyFrames().setAll(
new KeyFrame(movementTime,
new KeyValue(player.xProperty(),
player.getX() - movementDistance)));
xMovement.playFromStart();
}
// ...
}
请注意,循环计数保留为默认值,即1。