I may have a problem imagining the best solution for a collision detection related problem. I'm writing a 2D top-down game in Java with many objects that could collide. I am planning to use the approach to create a multi resolution map, with specific objects in specific resolutions of map squares, so that I can go around the O(n²) problem and narrow down the objects in an area that could be colliding.
I have to keep a list of all objects that are residing in each map square. However, since many or sometimes all objects are moving, I have to keep these lists updated all the time.
I guess using every render cycle of an object to update the map square lists will be quite resource consuming and will probably destroy the advantage I gained by using multi resolution maps to narrow down the number objects that could be colliding with another object.
My question is now, how to keep track of all objects and filling them into the according map squares? Is there an easy way, or should I maybe choose another concept for the collision detection?
I might have forgotte some details, if there is some more information I should provide, please reply.
Thanks in advance
Best regards
i assume that you have non moving objects and moving objects. the static objects needs to register themselves only once in the multi resolution map. the moving objects have only to check if they belong now to another square if they really moved.
depending on how you do the actual collision detection you only need to recheck if the moving objects traveled a certain distance. that is the case when you check collisions with an object in the current and all surrounding squares.
the squares far away from the players square usually also don't need to be checked every single physics pass. there is usually no action going on anyway.
Related
I have a side-scrolling platformer type game with procedurally generated terrain, see below. The pink circle is a dynamic body for the player, the green area is a single static body and each of the tiles is a fixture.
The player can move left and right and jump, via linear impulses. Now, most of the time this works fine, but every so often when I'm jumping around the player body suddenly falls partially through the ground body and gets stuck:
I can't discern any pattern to this, it just seems to happen at random. The degree to which the player falls through also varies quite a bit, sometimes you just clip a little bit into the terrain and other times you fall through 15 or 20 tiles.
I've found threads on here with similar problems of bodies ignoring collisions, one suggestion was to increase the velocityIterations and positionIterations arguments of the World.step() method. I've been trying that and it doesn't seem to matter. Another suggestion was to set the player body as a bullet. Again, tried it and it did nothing. So, any other ideas?
You should be doing something to coalesce your boxes so that you can cover the filled areas with a fewer number of objects. As is, it’s very inefficient and each gap is an opportunity for something to go wrong and allow for getting stuck inside as you report.
You definitely should look into computing the boundary and forming chain shapes on that boundary. This approach also means you won’t need to coalesce the boxes. You’ll want to still find a way to handle getting to the wrong side of the chain shapes but that’s still a cleaner approach, and besides, TOI calculations on chains will work way better than tons of separate little boxes.
Consider this, when you have a fast moving object slamming into a group of static boxes, even if the object is marked as bullet the system will try to ensure for each box that the object is about to penetrate that it will not penetrate them individually, and sequentially compute that, but this may still leave the dynamic object penetrating them in the end because they are all separate boxes! A chain shape is one single shape and will not have this problem, but you should still have some backup plan for if the dynamic object does somehow make its way to the wrong location.
Because of these nuances it is potentially useful to both have your static geometry wrapped in chain and space-filled with fixtures, and you can detect “stuck” states by looking for very obvious patterns in events (if on every single dt you get huge impulses from multiple static objects onto one dynamic object) and handle it accordingly.
I just started learning game development using Java.
I have created
ArrayList of class Zombie
ArrayList of class Bullet
Each of the object in the two ArrayList has a variable called rect of type Rectangle which surrounds their own graphics on screen.
My aim is to make an effect when any bullet meets any zombie.
My problem is I don't know how to do "any bullet meets any zombie."
My method: I used the rect variable to test whether both of the object have collided with each other by using the method rect.intersect(r). I'm testing every single bullet in the Bullet ArrayList to see if it has collided with any zombie in the Zombie ArrayList, which means I run through the two ArrayList completely per frame just to carry this feature out. There must be better ways..??
The only "better way" would be to run your collision detection on a separate thread so you can be detecting collisions while doing other logic.
This would not be the easiest thing to implement so unless you are experience massive slowdowns from collision detection I would recommend you continue as you are.
You could also try to narrow down the candidates for collision detection...
For example if some of the zombies/bullets are off screen you probably don't care if collision happens so you could completely skip said entity.
Yes you would have to first check if the entities are in the screen rect but that's only running through each list once and could potentially save you from running through a bunch of collision detection that you don't care about anyway.
TL;DR: If you aren't experience any massive performance drops I would try to just keep playing around with it and build your understanding of collision detection first, then worry about optimizations.
I hope it helps :)
I am making a program in Java in which a ball bounces around on the screen. The user can add other balls, and they all bounce off of each other. My question lies in the storage of the added balls. At the moment, I am using an ArrayList to store them, and every time the space bar is pressed, a new ball class is created and added to an Array List. Is this the most efficient way of doing things? I don't specify the size of the Array List at the beginning, so is it inefficient to have to allocate a new space on the array every time the user wants a new ball, even if the ball count will get up in the hundreds? Is there another class I could use to handle this in a more efficient manner?
Thanks!
EDIT:
Sorry, I should have been more clear. I iterate through the balls every 30 milliseconds, using nested for loops to see if they are intersecting with each other. I do access one ball the most often (the ball which the user can control with the arrow keys, another feature of the game), but the user can choose to switch control balls. Balls are never removed. So, I am performing some fairly complex calculations (I use my own vector class to move them off of each other every time there is a collision) on the balls very often.
Measure it and find out! In all seriousness, often times the best way to get answers to these questions is to set up a benchmark and swap in different collection types.
I can tell you that it won't allocate new space every time you add a new item to the ArrayList. Extra space is allocated so that it has room to grow.
LinkedList is another List option. It is super cheap to add items, but random access (list.get(10)) is expensive. Sets could also be good if you don't need ordered access (though there are ordered sets, too), and you want a Map implementation if you're accessing them by some sort of key/id. It really all depends on how you're using the collection.
Update based on added details
It sounds like you are mostly doing sequential reads through the entire list. In that scenario, a LinkedList is probably your best choice. Though again, if you only expose the List interface to the rest of your code (or even a more general Collection), you can easily swap in different implementations and actually measure the difference.
ArrayList is a highly optimized and very efficient wrapper on top of a plain Java array. A small timing overhead comes from copying array elements, which happens when the allocated size is less than required number of elements. When you grow the array into a few hundreds of items, the copying will happen less than ten times, so the price you pay for not knowing the size in advance is very small. You can further reduce that overhead by suggesting an initial size for your ArrayList.
Removing from the middle of the ArrayList does take linear time. If you plan to remove items and/or insert them in the middle of the list frequently, this may become an issue. Note, however, that the overhead is not going to be worse than that for a plain array.
I iterate through the balls every 30 milliseconds, using nested for loops to see if they are intersecting with each other.
This does not have much to do with the collection in which the balls are stored. You could use a spatial index to improve the speed of finding intersections.
About ArrayList in Java, the complexity of remove at the end and add one element is Amortize O(1). Or, you can say, it's almost efficient in most cases. (In some rare cases, it will be awful.)
But you should think more carefully about your design before choosing your data structure.
How many objects often in your collection. If it's small, you can free to choose any data structure that you feel easily to work with. it will almost doesn't lost performance for your code.
If you often find one ball in all of your balls, another datastructure such as HashMap or HashSet would be better.
Or you often delete at middle of your list, maybe LinkedList will be appropriate choice :)
I'd recommend working out the way in which you need to access the balls, and pick an appropriate interface (Not implementation) eg. If you're accessing sequentially only, use a List. If you need to look up the ball by ID, think of a Map. The interface should match your requirements in terms of functionality, not in terms of speed/efficiency.
Then pick an implementation, eg. HashMap or TreeMap, and write your code.
Afterwards, profile it - Is your code inefficient in the ball access code? If so, then try to optimise by switching to an alternate implementation thats more appropriate to your needs.
I'm writing a 2D platformer game using Java for Android.
Currently I have all game entities (except for the avatar, stored in an array of array of "Entity"
Entity[][]
Whenever I need to check something - such as what I'm going to draw on screen or for collision detection - I simply grab a small radius of items around the avatar and do whatever using a system of inheritance and polymorphism.
The problem is that this means I can only put one entity in a particular grid coordinate. This used to be quite okay for the most part - but now I have moving items (such as enemies or moving blocks) - which when they collide, end up deleting one another basically they get overwritten.
So what data structure should I use? I was thinking of something like
ArrayList<Entity>[][]
But that's going to be very expensive, and a waste of memory since duplicate items are the exception not the rule.
I was also considering separating the moving items into their own ArrayList, and looping through all of them, but that's an ugly solution.
So any ideas on what I could use? I want something which is pretty fast, but not too memory intensive.
A two-dimensional array for storing entities wastes memory (most blocks won't be occupied) and doesn't allow overlapping entities, as you noticed. With few entities, a simple ArrayList (no visible arrays involved) is probably going to be fully adequate.
If you have lots of entities, you could consider a quad-tree data structure or some other spatial indexing structure (check http://en.wikipedia.org/wiki/Spatial_index).
As a simpler and more "traditional" approach, how about keeping a two-layer view of your entities-- an ArrayList of all active (visible) ones, and an ArrayList of all inactive (too-far-away-to-care) ones? If performance matters, you can disable collision detection on the latter and perform little or no AI/maintenance on them.
What about you keep the entities as:
Entity[][]
And assuming you look-up entities, like:
Entity e = entities[i][j]
But keeping you enemies in a:
Map<String,List<Entity>> map
Where the key is the String made by concatenating i and j with a random middle character (e.g. "1.15" if i==1 and j==15). Now you keep the fast look-up of entities and also have fast look-up (albeit not as fast as an array) of enemies without the excess empty space.
Basically I have a rogue game I'm making, and am trying to implement dropped items for when the enemy dies. I've tried a couple different methods on how to do this, and none have been successful.
I was just wondering if you have any ideas on how you would go around such a thing. Thanks!
I haven't gotten to items in my current wip Roguelike engine, but here is an outline of my current plans:
Both map tiles and entities act as containers for entities. When an entity in a tile suffers an item-dropping event (i.e. normal death) you could just append the contents of its inventory list onto the tile's contents list.
I also plan to add logic for tile/entity capacity though, so you can't carry walls off (usually?), and tiles can't contain infinitely large piles.. Also since you probably want to control item drop frequency and type it is probably best to give entities a method that returns a list of inventory they dropped.
+1 to https://gamedev.stackexchange.com/ though, I didn't know that existed.