0

So I am making Plants vs Zombies in JavaFX. The best I could come up with for moving zombies and mowers etc was to execute each of them as thread. Now the issue is when do you check for collisions ? I tried using a while loop and it took forever and program just stopped. What should be condition for checking collision. Here is how I am doing:

while (true){
            for (Zombie z : zombies[0]){
                Shape a = Shape.intersect(z,mowers[0]);
                if (a != null){
                    mowers[0].takeHit(1);
                    z.takeHit(100);
                }
            }
        }

Issue is that zombie takes atleast 20 seconds to come till mower.
How do I use this loop more efficiently. As in how to replace the while loop more efficiently ?

For further reference, this is how zombie is moving

Thread.sleep(toStart*1000);
TranslateTransition translate = new TranslateTransition();
z.t = translate;
translate.setToX(-(1650+155));
translate.setDuration(Duration.seconds(30));
translate.setNode(z);
translate.play();
z.countdown.await();
node.remove.acquire();
node.root.getChildren().remove(z);
node.remove.release();
  • One approach is show [here](https://stackoverflow.com/a/39188588/230513). – trashgod Nov 29 '19 at 09:27
  • Creating a seperate thread for every object on the screen is a terribly idea. You'll end up with an excessive amount of threads all fighting for processor time slowing down everything and you've also created yourself a nightmare when trying to synchronize everything. If the synchronisation is done properly, your threads will also need to spend much time waiting for other threads to release locks on data. I see 2 options here: a) update the gui stepwise. You could e.g. use `Timeline` which would allow you to avoid synchronisation entirely, since none of your code runs concurrently. – fabian Nov 29 '19 at 13:48
  • b) Create a single thread doing all the updates on a set of data seperate from the gui and regularly doing updates to the gui using `Platform.runLater`. This requires you to ensure the update rate is limited though. Otherwise all the runnables will slow down the gui updates to the point where the gui is effectively frozen. – fabian Nov 29 '19 at 13:51
  • Note that the approach I [cited above](https://stackoverflow.com/questions/59101153/javafx-collision-with-multiple-threads#comment104436344_59101153) and @fabian's `Timeline` suggestion do the waiting in the background, invoking `Platform.runLater()` as required. The last example examined [here](https://stackoverflow.com/a/37370840/230513) mixes `AnimationTimer` and `Timeline`. – trashgod Nov 29 '19 at 16:39

0 Answers0