简体   繁体   English

如何使用Slider动态更改JavaFX AnimationTimer的速度?

[英]How can I dynamically change the speed of a JavaFX AnimationTimer with a Slider?

I'm working on a variant of the Conway's Game of Life called Wireworld, and I want to have a slider control so the user can change the speed of the simulation at will. 我正在研究Conway的《人生游戏》的一个变种,叫做Wireworld,我想拥有一个滑块控件,以便用户可以随意更改模拟的速度。 I think I just have a simple math hiccup, but what I'm doing is getting the difference between the current nano time and the last update, then dividing by 1,000,000,000 (to convert to seconds), and checking to see if it's greater than or equal to the update time (0.016667) divided by the speed slider value (a value between 0.05 and 1.0). 我想我只是遇到了一个简单的数学难题,但是我正在做的是获取当前nano时间与上次更新之间的差,然后除以1,000,000,000(转换为秒),然后检查它是否大于或等于等于更新时间(0.016667)除以速度滑块值(介于0.05和1.0之间的值)。

Here is the code as I have it... 这是我的代码...

new AnimationTimer() {
    private long lastUpdate = 0;

    public void handle(long currentNanoTime) {
        if((double)((currentNanoTime - lastUpdate) / 1000000000) >= (updateTime / speedSlider.getValue())) {

And then at the end of the update cycle, I change lastUpdate to the value of currentNanoTime. 然后在更新周期结束时,我将lastUpdate更改为currentNanoTime的值。

Is there something wrong with this approach? 这种方法有什么问题吗? The animation moves very slow at the default speed of 0.5, and there's no noticeable difference when moving the slider to either extreme. 动画以默认速度0.5移动时非常慢,并且将滑块移至任一极端时都没有明显差异。

It seems the problem was where I was casting the two longs in the conditional. 看来问题出在我在有条件的情况下投下两个多头。 Instead of this... 代替这个...

if((double)((currentNanoTime - lastUpdate) / 1000000000) >= (updateTime / speedSlider.getValue())) {

I needed to do this... 我需要这样做

if((((double)currentNanoTime - (double)lastUpdate) / 1000000000.0) >= (updateTime / speedSlider.getValue())) {

I suspected this was the problem. 我怀疑这是问题所在。 The problem being that, like integer division, even if you convert it to a double, the division happens first, so it would be a round number, rather than an accurate floating point number. 问题是,就像整数除法一样,即使将其转换为双精度,除法也会首先发生,因此它将是一个整数,而不是精确的浮点数。 I guess I just needed to take a break and think about it. 我想我只需要休息一下并考虑一下。 Works fine now! 现在工作正常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM