Avoiding nested for loops in 2D game engine - algorithm

I am creating a 2D game.
There are many objects, each has a width, a height, and X and Y coordinates.
Each object is stored in an array of it's class:
the player
allies
enemies
obstacles
power ups
bullets shot by the enemies
bullets shot by the player & allies
To make the game work, I need to obviously detect if two elements occupy the same space (let's call it "collission") , so that
the player can collect power ups
nobody can pass through obstacles
the allies can shoot the enemies
the enemies can shoot the allies
friendly fire can be either enabled or disabled
this needs to be checked every frame, 60 times per second.
What I have been doing so far, is loop through each class, and then loop over each class that it can interact with.
For example:
foreach (ally_bullets)
{
foreach (enemies)
{
if ( collision detected between enemy and bullet )
{
remove the bullet and the enemy
}
}
}
It makes sense and it works, but it's very resource intensive as the game gets more complex. The more elements there are, the longer this nested for loop takes to render, ultimately reducing the frame rate. Even if I am trying to run as few loops as possible.
What's a better way of solving this then nested for loops?

A common solution is to use Polymorphism, in which you have a base class (in this case Object) which gets inherited by other classes (such as Player, Bullet, Enemy, etc). Instead of each of these having an individual array, you would have a single array (or typically more appropriate, a vector). Now you just loop through that one array having each Object do their updates, and have their updates checked against every Object in the array.
This 'vector-wise' updating is usually setup as a Messaging System. Now whenever an inherited Object receives a message (such as 'hit by bullet'), that object checks if it cares about that message. If so, accept the message, else ignore it.
This is (in my opinion) the better way to handle what you are trying to accomplish, which I believe is what you were asking.
If you are still using arrays for this, I am going to assume you are still fairly new to programming, and I am going to suggest sticking with what you have now. It will absolutely work (providing you know how to finish your project), and when you finish this and start to learn something more advanced you will see both the shortcomings of the way you are doing it, and the benefits of it).
If you do see some lag arise, it will likely be from your drawing methods long before this kind of interactivity checking becomes a bottleneck.
Either way you go, collision detection itself and rendering are going to be the main areas your cpu will be eaten up, providing your arrays stay within reasonable ranges.
Edit:
Another thing that will help you should you pursue the topics I mentioned is the Observer Pattern, also known as the Listener Pattern.

Related

How Ruby arrays behave internally when deleting an element?

I am designing a game in Ruby in order to learn the language and my game needs to be in a constant cycle of deleting items from an array and adding them to another one, than deleting from the other one and readding to the first one.
I want to know what happens internally when I call Array.delete(). I'd rather use a linked list for my game since deleting from and adding to a linked list is way more efficient than on an array. However, Array is the only data structure I've come accross in Ruby so far. Is it really the only one available?
edit: It's a basic shoot'em up game where the enemy ships can shoot bullets at the player. In order to avoid having to allocate a new bullet every time an enemy fires at the player, I allocate a lot of bullets before the game starts. When an enemy shoots, he picks a bullet from the list of available bullets and puts it in the list of "active" bullets. The class responsible for drawing the bullets on the screen only draws those bullets in the list of acitve bullets. When a bullet leaves the screen, it goes back to the list of available bullets. That's where all the shuffling comes from...
It's easy to implement a linked list in Ruby, but the one time I actually did it, performance was exactly the same as using an Array. The better algorithm in Ruby was exactly balanced by the speed of the internal C code.
Now, I wasn't trying to delete things in the middle of my Array.
For your case, I think it's safe to say if the arrays are short, then the algorithm doesn't matter and you will be fine using the built-in Array class. If the array is long, then no doubt some sort of map could be constructed whereby deleting things from the middle of the Array would not require repacking the array and its quadratic time complexity.
Really, you should first implement your game in the simple and direct way. You shouldn't stir in complexity in the beginning without even knowing what it buys, if anything. Who knows, you may even find that some other part of the game uses more time.
And should you find that indeed you are bogged down with Array deletions, the next step is to add a map or perhaps, yes, a linked list or tree implemented in Ruby. And if that isn't fast enough, with your encapsulated Ruby solution and a set of tests, you would be in a good position to write a C extension, and you would know almost exactly the benefit.
Use Hash. It is more efficient than Array.

How do you handle objects moving between quads when using quadtrees?

I'm trying to use quadtrees for collision detection in a game I'm making, but I'm not sure how to handle objects that might be moving between different quads?
The only way I can think of it is by clearing out the whole tree each frame, and then adding everything back in there, but that seems like that can get cpu intensive and not very efficient. Do you check each object every frame to see if it has moved outside the boundry of it's current quad, and if so then remove it and readd it? That again seems like it can be pretty inefficient because you'd be performing collision checks on every moving object every frame.
Also, regarding quadtrees but unrelated to objects moving around in them, how do you handle multiple objects in the same quad? Most sites that I've read about them on say that you should only have one, maybe two, objects in a quad, and if you get more than that then push them down in the tree. What if you had a situation like this? You have three circles and they are all on the edges of the level below them so they can't go any further down, but there is three all in the same level, which people say you shouldn't have.
I don't think it's particularly inefficient to implement your suggestion: check to see if an object has moved outside its quadtree, and if so then remove and re-add it. Any object which moves from one frame to the next will need to have some collision detection performed on it, surely? And the quadtree operations are only performed if it moves quadtrees, and the CPU time spent there are probably overshadowed by the CPU time doing the more precise "Does object A touch object B?" computations. So I don't know that you can do better.
On your 2nd question: I don't know how other people implement quadtrees, but I allow objects to occupy more than one quadtree, precisely for the reason you've given in your diagram (when an object straddles a boundary). So an object has a "current list of quads" instead of a "current quad".
Removing/re-adding can be optimized by moving up the quad tree instead of removing the item from the tree completely and then re-adding, i.e. move to the "parent" quad, and then have the "parent" add it - if it doesn't fit in the "parent", go to the "grandparent", etc.
As for your second concern, you will need some flexibility - if all 3 are on an edge, then you can't lower them - but that should be (pardon the pun) an edge case.

How should platformer game's solid objects be implemented efficiently?

I have been trying to write a platformer engine for a few times now. The thing is I am not quite satisfied with my implementation details on solid objects. (wall, floor, ceiling) I have several scenario I would like to discuss.
For a simple platformer game like the first Mario, everything is pretty much blocks. A good implementation should only check for necessary collision, for instance, if Mario is running and at the end of the way, there is a cliff, how should we check for collision efficiently? Should we always check on every step Mario is taking to see whether his hitbox is still on the ground? Or is there some other programming way that allows us to not handle this every frame?
But blocks are boring, let's put in some slopes. Implementation details-wise, how should slopes be handled? Some games such as Sonic, have this loop structure that the character can go "woohoo" in the loop and proceed.
Another scenario is "solid" objects (floor, ceiling, wall) handling. In Megaman, we can see that the player can make himself go through the ceiling by using a tool to go into the solid "wall". Possibly, the programming here is to force the player to go out of the wall so that the player is not stuck, by moving the player quickly to the right. This is an old "workaround" method to avoid player stucking in wall. In newer games these days, the handle is more complex. Take, for instance, Super Smash Brawl, where players can enlarge the characters (along with their hitbox) The program allows the player to move around "in" the ceiling, but once the character is out of the "solid" area, they cannot move back in. Moreover, sometimes, a character is gigantic that they go through 3 solid floors of a scene and they can still move inside fine. Anybody knows implementation details along these lines?
So here, I know that there are many implementation possible, but I just wanna ask here that are there some advanced technical details for platformer game that I should be aware of? I am currently asking for 3 things:
How should solid collision of platformer game be handled efficiently? Can we take lesser time to check whether a character has ran and completely fell off a platform?
Slope programming. At first, I was thinking of physics engine, but I think it might be overkill. But in here, I see that slopes are pretty much another types of floor that "push" or "pull" the character to different elevation. Or should it be programmed differently?
Solid objects handling for special cases. There might be a time where the player can slip into the solid objects either via legal game rules or glitches, but all in all, it is always a bad idea to push the player to some random direction if he is in a wall.
For a small number of objects, doing an all-pairs collision detection check at each time step is fine. Once you get more than a couple hundred objects, you may want to start considering a more efficient method. One way is to use a binary space partitioning (BSP) to only check against nearby objects. Collision detection is a very well researched topics and there are a plethora of resources describing various optimizations.
Indeed, a physics engine is likely overkill for this task. Generally speaking, you can associate with each moving character a "ground" on which he is standing. Then whenever he moves, you simply make him move along the axis of the ground.
Slipping into objects is almost always a bad idea. Try to avoid it if possible.

How do I handle the creation/destruction of many objects in memory effectively?

Im in the process of making a game of my own. One of the goals is to have as many objects within the world as possible. In this game, many objects will need to be created in some unpredictable period of time (like a weapon firing will create an object) and once that projectile hits something, the object will need to be destroyed aswell (and maybe the thing it hits).
So i was wondering what the best way to handle this in memory is. Ive thought about creating a stack or table, and adding the pointers to those objects there, and creating and destroying those objects on demand, however, what if several hundred (or thousand) objects try to be created or destroyed at once between frames? I want to keep a steady and fluid frame rate, and such a surge in system calls would surely slow it down.
So ive thought i could try to keep a number of objects in memory so that i could just copy information into them, and use them without having to request the memory for them on demand. But how much memory should i try to reserve? Or should i not worry about that as long as the users computer has enough (presumably they will be focusing on the game and not running a weather simulation in the background).
What would be the best way of handling this?
Short answer: it depends on the expected lifetime of the objects.
Usually, the methods are combined. An object that is fairly static and is unlikely to be removed or created often (usually, players, levels, certain objects in the levels, etc) are created with the first method you described (a list of objects, an array, a singleton, etc) The exact method depends on the game, and the object being created.
For short term objects, like bullets, particle effects, or in some game, the enemies themselves, something like object pool pattern is usually used. A chunk of memory is reversed at the beginning of the game and reused throughout the course of the game for bullets and pretty particle effects. As for how much memory should I reserve?, the ideal answer is "As little as possible". Unfortunately, it's hard to figure that out sometimes. The best way to figure it out is to take a guess at how many bullets or whatnot you plan on having on screen at any given time, multiply by two (for when you decide that your bullet hell shooter doesn't really work to well with only 50 bullets) and then add a little buffer. To make it easier, store that value in a easily understood #define BULLET_MAX 110 so you can change it when the game is closer to done, and you can reasonably be sure that the value isn't going to fluctuate as much. For extra fun, you can tie the value into a config variable, and have the graphics setting affect it.
In real time games, where fluidity is critical, they often allocate a large chunk of memory in the beginning of the level and avoids any allocation/deallocation in the middle of the game.
You can often design so the game mechanic prevents the game from running out of memory (such as increasing the chance of weapon jamming when the player shoots too much too often).
Ultimately though, test your game in your targeted minimum supported machine, if it's fast enough there then it's fast enough and don't overcomplicate your code for hypothetical situations.

Collision detection delegate scheme

Hey guys! My physics engine is coming along quite nicely (thanks for asking!) and I'm ready to start working on some even more advanced junk. Case in point, I'm trying to set up my collision engine so that an arbitrary delegate can be notified when a collision occurs. Let me set up a scenario for you:
Say we have object A, object B, and object C in the physics simulation. I want to be able to inform a delegate about a collision between A and B, AND inform a potentially DIFFERENT delegate about a collision between A and C.
A little background information: I have a known interface for the delegate, I have the potential of storing state for my collision detector (but don't atm), and have the ability to store state in the objects themselves. Similarly, I use this delegate model to handle collision resolution, simply setting the physics engine as the delegate for all objects by default, allowing the user to change the delegate if desired.
Now, I already tried having each object store it's own collision delegate that would be informed when a collision occurred. This didn't work because when the objects had the same collision delegate, the same collision was handled twice. When I switched to only using the delegate of the first object (however that was decided), the order of simulation became an issue. I want to use a dictionary, but that introduces a significant amount of overhead. However, that seems like the direction I need to be heading.
So here's the question: fight to the death over a suitable solution. How would YOU solve this problem?
I must say that it's a bit odd that two objects can have different delegates (at a collision) and still it would be bad if two identical delegates fired at a collision. I seems like they should both fire all the time or only one of them should. Consistency is what bothers me here.
Explaining that would help some more.
Second, if you use the naive version of holding a delegate for each object and then conditioning activating its functionality ("if (!some boolean indicating this delegate was fired already) {do something}"), this could be solved with a very small overhead.
It works, but I don't like this kind of code.
My suggestion (a bit complex, so think about it before working on it) is to try to focus on a manager object which would go over all the delegates and invoke the two that where relevant to the collision.
For instance, A and B collide, and the manager is invoked with them as parameters. You now can cycle through all the delegates known to the system (assuming they are few) and fire the ones that match "delegate == a.del or delegate == b.del".
This comes at a greater overhead, but if we are talking about a small number of delegates, if will make very little difference. On the other side this will allow you to expend your collision detection engine in this area further more in the future (like the existence of more then one delegate per object).

Resources