Application time / flow

I am writing a simulation in Java in which objects operate under Newtonian physics. An object can have a force applied to it, and the resulting speed makes it move around the screen. The nature of the simulation means that the objects move in discrete steps depending on the time elapsed between the current and previous iteration of the animation cycle; eg

public void animationLoop() { long prev = System.currentTimeMillis(); long now; while(true) { long now = System.currentTimeMillis(); long deltaMillis = now - prev; prev = now; if (deltaMillis > 0) { // Some time has passed for (Mass m : masses) { m.updatePosition(deltaMillis); } // Do all repaints. } } } 

There is a problem if the animation stream is delayed in some way, causing a large amount of time for the ellipse (the classic case is under Windows, in which pressing and holding to minimize / maximize prevents redrawing), which causes objects to move at an alarming speed. My question is: is there a way to determine the time spent in the animation stream and not the acceleration time, or can someone suggest a workaround to avoid this problem?

My only thought so far is to keep deltaMillis some upper bound.

+4
source share
4 answers

Have you considered using something like a timer instead of spinning in a loop?

 TimerTask tt = new TimerTask(){ long prev = System.currentTimeMillis(); public void run(){ long now = System.currentTimeMillis(); for (Mass m : masses) { m.updatePosition(now-prev); } prev = now; } } new Timer(true).schedule(tt, 1000, 1000) ; 

This way you guarantee at least some delay between updating your objects, so you donโ€™t need to have a bunch of replicators sequentially, like in a while (true) loop, and if the thread is delayed, you will not get the task to execute the task again from the documents: "When executing with a fixed delay, each execution is scheduled relative to the actual execution time of the previous execution. "

+6
source

I found javax.swing.Timer.html especially useful for this. Here is an example that models elastic collisions between spherical particles and the walls of a container.

Appendix: This related approach can help separate the model from the view. A separate stream models the evolution of the system, and the view takes a โ€œsnapshotโ€ of the model at a fixed speed.

In any case, I limit the speed to accommodate the slowest target platform.

+3
source

You might like to read an article entitled "Java: Getting Time in ThreadMXBean".

Basically, there is a ThreadMXBean class that allows you to spend time, in particular Thread . I have not tried this, but the methods (and examples from the article I mentioned) look promising, so I think you can accomplish what you want with this.

+1
source

I would use an animation library to create animations instead of reinventing the wheel. Here are two good options:

0
source

Source: https://habr.com/ru/post/1306908/


All Articles