How to Check for 2D Collision Without Checking Every Object - java

I'm being really ambitious and working on a 2D Shoot 'em Up game that will have, hopefully, hundreds of entities running around.
What I'm having trouble wrapping my brain around, is how the bullet will detect when it makes a collision with an object, without it checking for every object on the map. The reason is that I feel that if I have four dozen bullets on the screen, each checking for collision with every entity on the map, every cycle, I will see some fairly significant performance loss.
So what would be the best way to detect for collisions without checking every single entity?
I can handle the collision algorithm when I have my two objects, I just can't seem to find a way to get those two object to see each other without checking everyone else first.
I'm working in Java and OpenGL with (soon to be textured) QUADS.

You should investigate quadtrees; they're often used for efficient 2D lookup.

Related

How to add octree support in JBullet

I am making a voxel-based game where large structures made of voxels can collide with each other. The game runs smoothly until two structures get to close to each other where it quickly drops to about 3 updates/second.
My current solution to adding these colliders to JBullet is by using a compound shape and using a greedy-meshing algorithm to make larger colliders out of adjacent blocks. While this is a drastic improvement over each voxel having its own collider, it still isn't fast enough to simulate large structures colliding.
I did a bunch of research and it seems that octrees are the only way to make this run in real time, but can't figure out how to add support for them in JBullet.

What is the most efficient way to store a static list of Objects?

I'm trying to store a list of different Enemies. Each Enemy has an origin and can only spawn in its Location of origin. Each enemy also has a difficulty and should be stored with enemies of the same difficulty.
I imagined it as a static 3D array of Enemies like this:
Enemy[mountain][2][5] = new Enemy("troll")
Where the fields are (from left to right) Location, difficulty, index.
Each location the player enters will populate an ArrayList of Enemies from this static array.
Is there a more efficient data structure to use in this scenario?
(This list will be hard-coded and should not be altered during the course of the program)
edit-
I was hoping to optimize the access time. This game will generate a number of locations, each one needing to randomly draw Enemies from the list based on their origin and difficulty.
As per request, I will put some more thought into the use case of this program. Once I have a proper solution I will update. (Thanks)
It is conceptually wise not a good idea.
You really do not worry about performance at this point. You worry about creating a useful, helpful object model that allows you to write elegant, easy-to-read and easy-to-enhance code.
Using a 3D-array achieves none of these goals.
In other words: you step back; and think hard about the "use cases" that need to access your Enemy objects. And coming from there, you decide if you should go with different Maps for example; or different Sets, ... instead of using a 3D as central "storage point".
Edit, given your comment: there are two sides here:
Arrays are very inflexible in Java. You can't change their size dynamically. And beyond that, they are really "ugly" to use: this going through "3 dimensions" might be convenient for a certain "ascess path"; but it could make other things very hard (like when searching for a certain enemy, then you have to do this 3-dim iteration stuff ... as said: ugly)
One should try to make designs that are "open" for changes that have a high rate of "taking place". Example: you have a fixed number of enemies today; but assuming your "game" works out for you; you will sooner or later (rather sooner) want to enhance it; for example by allowing dynamic add/removal of enemies. Then a lot of the code you wrote using the 3-D array ... would become a real obstacle.
Beyond that: yes, in a "game world", there should be one component that is responsible for keeping track of all elements in the game. But: how this component internally organizes things is more of an implementation detail. You should focus on putting "helpful" methods on that GameWorld first; or as I put it before: understand the ways how your code will need to access/iterate/search enemies to perform the game itself. And then you look into data structures that support these "use cases".
Finally: assuming that this is a learning exercise - you can still start with a 3d array. It will teach you a lot; I am merely pointing out: you would not do that in a more "real world" application; and if you go for this option, you will soon be confronted with certain limitations/obstacles; just by the nature of your solution.
What comes to mind for me is a map. The location is the key and the value would be a List of objects that represents the enemy and its location - let's call it an EnemyLocation object that contains an Enemy and its location (or you could change Enemy to contain its location which seems like a good idea, but I don't know your code). So, when a player enters the "mountain" region, you do something like enemies.get("mountain") and you get back a List of Enemy objects (or EnemyLocation objects)

Handle Entities for Collision

I'm writing a 2d Top-down RPG using the LWJGL alongside with Java 1.6. By now, I have the rendering and input methods working fine and just started to program the game's logic.
So I have a class called World, which holds an ArrayList of Entities. I want to implement simple collision in the game (using intersecting squares), which should be no problem. The only problem I now have is how to access single cells of my List without having to iterate all over it. I have only been able to come up with collision methods which are executed inside each Entity and iterate over all of the entities in my World. That is not fast at all, but I really don't know what to do in order to make it faster.
My game is tile based, but the movement is not tile-to-tile, one can walk smaller portions, which avoids me to simply use a two-dimensional array...
Is there a standard way to handle entities and their collisions? (or maybe a way to handle collision between entities which are located inside an ArrayList?)
The standard way to handle colliding entities is by space partitioning. Your world is a 2 dimensional plane made of discrete points.
Each piece can be located on one of the points. The amount of the points determines the resolution of the plane- the more points, the better visual effect, the more calculations you have to perform. This is the trade off.
You can maintain a map between the location of an entity and the entity itself, where the location is represented by an object that overrides equals and getHashCode. The location object contains two members- the X and Y coordinates.
Note- you have to override in a proper and efficient manner.
So you you can access each entity very quickly if you know its coordinate, reshuffling is simply removing an entity and adding it with new coordinates (this can be optimized for locality) and collision detection is trivial- just check whether the same location is occupied by a certain entity.
I would also refer you to this question on SO.

Java game development. Making a tile-map faster. Advices on optimisations

I'm trying to make a fully-automated game engine which needs to be working based on the events. The problem I'm facing is that I've made a map class and it's initialized in the game class. It's almost static and only one map exists for a game. New maps are loaded by clearing the objects in the current map and adding new maps. You can see the source of the map class here.
http://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/map/Map.java
The main problems comes in the collision detection, where I'm using the brute-force collision detection where I should not. This slows down the game a lot and I wanna check the collisions only for objects which are nearer to the object. I've been using the MapLoader interface to construct the maps. I'm thinking that calling the collision() method of the objects in another thread might help. How-ever it all the map objects are updated in the Game class.
Here's the game class if in case it might help
http://code.google.com/p/game-engine-for-java/source/browse/src/com/gej/core/Game.java
There's another problem that some-times, the objects aren't destroyed. I'm calling the map's removeObject() method but it takes a 1-second delay and some times wont remove at-all.
It gives me 48-64 fps in a platform game with 158 objects in the game. But in a space-invaders style game, it gives me only 20-30 fps. Any advice on optimization is greatly appreciated...
If anybody could get me a tutorial for binary spacing etc., I would be thankful.
Two suggestions by looking at your code: first thing is that you should try to minimize object allocation in collision detection, don't create new Rectangles, work on data you already have by writing directly the collision detection algorithm.
Second an more important thing: a collision detection engine should work by using two levels:
a coarse level of collision already excludes objects that are surely too far to collide (you can use many techniques here, like a binary spatial partition algorithm of big colliding blobs, or hierarchical structure of objects)
a fine level which will compute specific details for the collision that can occur, with more precise algorithms

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

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.
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!)
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.

Categories