Random Falling Objects and Collision Detection Method
I'm programming a game where you can catch objects falling from the top of the screen (bitmaps). These bitmaps will all have the same image file. However, I want a random amount of them to fall infinitely (until the game is "over"). My problem now is coming up with the algorithm to detect the catching of these randomly produced bitmaps. I can register a catch when I have just one image falling, but I don't know how I'll implement multiple images falling and be able to implement collision detection. So far, I came up with two ideas. One of them is to have a queue, and each falling object gets put in the queu开发者_如何学Ce when it is created. The program will only ever detect if the box has caught the object in the first position of the queue. If it (a) is caught or ( reaches a certain point on the screen, that object will then be dequeued. The other idea I had is more of a question - am I able to create a class for this falling Object, and have a method inside it that handles the collisions? One that is always listening for a collision whenever a new instance of that class is created?
Let me know your thoughts and suggestions please!
If you just want to check for collisions between the falling objects and the catching box, you might just sort the objects by their height - using insert sort for example. If all objects have the same speed and size this would be even easier, since then you could just use a queue.
Then start with the lowest object and check until you get objects that are too high for a possible collision (if the box can vary height, this might vary too).
Example:
| 6 |
| 5 |
| 3 4 |
| |
+----2---------+ <-- if you reach an object at this height stop
| 1 |
| |__| |
+--------------+
Suppose you have 6 falling objects. If they are sorted you now can iterate through the list and check for possible collisions. If you reach the height threshhold (where object 2 is) you can stop, since they can't collide yet (no need to check objects 3-6).
Note that there are other more sophisticated yet faster approaches, but this should get you started.
Edit:
This is a sort of sweep and prune algorithm, in case you'd want to google it.
Another approach could be to calculate the ETA (estimated time of arrival), i.e. for each new object calculate the time when it should cross the threshold line. Then sort by that time and check all whose time difference is <= 0 (they crossed the threshhold line). This would work well for objects of different size and speed and with the catching box being at fixed height.
精彩评论