How do those java sand games keep track of so many particles?

若如初见. 提交于 2019-12-04 23:55:05

问题


Can anyone shed any light on how a program like that might be structured?

What java classes would they employ to keep track of so many particles and then check against them for things like collision detection? Particles need to know what particles they are next to, or that they're not next to anything so they can fall etc.

Here's an example, incase you're not sure what a sand game is.


回答1:


Arrays, mainly.

  • A one-dimensional array of actively moving grains, represented by two coordinates (and possible a velocity if you want gravitational acceleration).
  • A two-dimensional array of bools (or colours), representing the fixed parts of the world.

The simplest physics model is to remove a grain once it is at rest (e.g. when the world positions below, below to the left and below to the right are filled): instead, the corresponding world coordinate is filled in. This keeps the calculations manageable. Allow a grain to shift down if either the left or right below world coordinate is free. Grain collisions between moving grains can be ignored without loss of much verisimilitude.

(I can't quite get over how much CPU power we've got to spare these days!)




回答2:


The simple version can be implemented without much trouble on a loose friday night (like I did just now). Simply make a program with a 2D array (of bytes, ints, whatever) representing your field. In each tick, iterate over all the elements and do a check:

  • If the field below (array[x][y+1]) is empty, move 1 spot down (= set [x][y] to empty, [x][y+1] to occupied)
  • Else, if [x-1][y+1] is empty, go there.
  • Else, if [x+1][y+1] is empty, go there.

That's the basics. Next you have to add checks like not 'repeating' the calculation for a grain (set a flag at the new position that's checked at the following iterations).

I followed this tutorial, it's quite good, not too long but still points out common pitfalls and things like that.



来源:https://stackoverflow.com/questions/3460849/how-do-those-java-sand-games-keep-track-of-so-many-particles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!