Managing collision detection in games - language-agnostic

So my question isn't about the how-to of collision detection, but is more of a broad 'what code should own collision detection'. I've written some game in the past(relatively simple 2D Flash games) and it got me thinking of which code should own collision detection?
Let me clarify - say in a game I have a group of enemies and a group of projectiles the player has fired. So in the past I've had say an EnemyManager class, that every frame updates the positions of the enemies and likewise for the player projectiles had a PlayerProjectilesManager class that moved around the bullets. That's cool - everything is fine and dandy. But then, I decide I want the bullets to affect the enemies(crazy I know!). So that means somewhere in the code I need to:
Figure out which bullets and enemies are colliding(I don't care how for this question)Figure out the response to each collision
So basically what I've done in the past is just have the EnemyManager class take 'ownership' of the collisions, and during its update loop it finds the player bullets that collide with enemy bullets(i.e. Step 1) and also calls code for both objects to handle the collision (e.g. the enemy losses health, the bullet disappears) (i.e. Step 2). So I've given control of the collision detection and collision 'reaction' to the EnemyManager.
A couple comments about that:
It feels vary arbitrary to me that the EnemyManager is in 'control' instead of the PlayerProjectilesManager
Both collision detection and collision 'reaction' are handled by the same owner, this isn't a requirement from my point of view
What's forming in my mind is a 3rd party entity managing collision detection. For instance have a CollisionManager which has code that know's which other Managers need to have collisions detected. That leads to other questions like what interfaces do the 'Managers' need to expose for efficient collision detection without exposing too many innards to the CollisionManager. Then I suppose the CollisionManager what broadcast some sort of an event, containing which 2 objects collided etc... and perhaps the EnemyManager/PlayerProjectilesManager could separately listen for these events and react accordingly and separately. Starting to make sense in my mind. :)
Thoughts? Almost every game has collision detection, so I'm sure this has been discussed before. :)

this is a nice question. Personally, I would not complicate it so much by using "Managers". Let's say we have a GameEngine, which runs the game in its main loop. This main loop could consist of 3 steps: get the user input, update the state of all objects in the game (based on the user input) and finally draw everything again on the screen.
Everything about the collision detection is done in the second step - when updating the objects' state. Let's say all objects in the game are stored in a pool. This includes the player, the bullets, the enemies and even the world (if you'd like the world to be affected as well somehow). All the different objects could have some common properties - they could be Drawable, Movable, Collidable e.t.c. (think like implementing an interface or extending a base class to have these properties)
For each of these properties I would have a class that do something with all the objects in the pool. Like Mover.moveAll(objectsFromPool). This will move all objects, which are Movable.
The same for collision detection -> after we've relocated the objects with the Mover, then we check for collision with CollisionDetector.cehckAll(objectsFromPool). This checkAll() method will do the actual collision detection between the objects themselves, knowing their coordinates. If an object is Collidable, the CollisionDetector will invoke its method onCollide(withOtherObject) and then the object itself reacts properly, depending what other object hit it. Let's say, if the player is touched by the enemy body, they will both step back for example. If a bullet is hits by another bullet - they will both be marked for deletion. If the enemy is hit by a bullet, then some damage will happen and the bullet will be marked for deletion. All these reactions should be in the corresponding objects themselves.The collision detector applies its algorithms to detect collision between any two objects and then invokes their onCollide(withOtherObjct) method.
If an object is not Collidable, it will be simply ignored by the CollisionDetector (for examples rain particles or dust are not Collidable).
I hope I managed to express myself correct :)

Questions specific to game development are best suited to https://gamedev.stackexchange.com/ by the way.
So in the past I've had say an EnemyManager class
I consider any SomethingManager class to be a sign that your code isn't organised accurately yet. For the most part, objects should manage themselves. If they can't, that implies there is some external information about them, and that information probably has a representation more specific than 'manager'. 3 game-specific examples might be GameWorld, GameRegion, or GameLevel. Enemies exist within a world, or a region of the world, or a current game level, so have such an object maintain its list of enemies.
and likewise for the player projectiles had a PlayerProjectilesManager class
Projectiles too would live in some sort of game space, a world, region, or level.
By now, you can probably guess that one of the above objects can (and probably should) be responsible for owning all the above objects (perhaps indirectly, via a container class, but not via a heavyweight manager of any sort) and responsible for detecting collisions and resolving them.

Related

Whats the best way to make collidable objects without Tile2D?

I'm currently trying to make a small platformer, but don't want to use Tile2D (specific reasons), what should I use instead to make platforms (objects the player can collide with).
At the moment, I have a List with every Rectangle the player can collide with and I go through every Rectangle when I want to check collisions, but I find that to be very clunky.
What should I use to make platforms, the player etc. I haven't used Box2D yet, dont know if its the thing I need and am also not sure wether Scene2D is the thing I am looking for. Any tips would be appreciated. Not sure if this is the right place to post this, but its worth a try.
Don't mix two things:
Box2D is a physics engine that allows you to simulate physical world with its whole actions like collisions handling, applying forces or velocity etc
Scene2D is a framework to "clean up" handling objects you want to manage - by definition it is scene graph that allows you to treat bunches of objects as single objects (groups) and apply for them some actions (like setting position on the screen)
So basically when Box2D is more about how objects will behave themselves during application running the Scene2D is more about how you write your code before application running.
Of course Scene2D is very helpful if you want to implement your own mechanism of collisions (like you wrote - you have rectangles array, then iterate over them and check their positions... etc) but the Box2D deliveres you this mechanism so you don't have to do nothing to check just tell the application what to do when collision will occurs.
Then it is problem about is it worth to implement your own collisions mechanism. The most frequent answer I guess is - if the game is simple and the mechanism will be then yes. If not just use physics engine - do not invent fire again ;)
To read about Box2D and learn how to use it visit:
Libgdx box2d intro
Box2D official manual
To read about Scene2D:
Libgdx Scene2D intro
This tutorial

Which AS3 physics engine can replay a simulation consistently?

I'm currently using the Nape physics engine for a "Peggle" style game in ActionScript 3.0.
It is very easy to use, and runs smoothly. However, The only difficulty I'm running into with Nape is replaying the exact same simulation.
Even if I supply it the same timestep value throughout the entire gameplay, it seems to have enough "error" in the calculations that the ball hits different pegs every once in a while (starting the round from scratch), sometimes even resulting more or less lit pegs.
So my question is:
Is there any other physics engines for Flash that can reproduce a given simulation EXACTLY the same each time it is relaunched?
EDIT:
The idea of "recording" the data on every-frames and playing it back was tossed around other forums I've asked this question. But unfortunately, the "replay" feature is not so much for the same user to view his/her own ball-drop scenario. It would be used for sharing between players on different machines (ex: client reports a bug with ball drop seeded a value 1234, we punch in 1234 and should be able to see the same issue).
So if we pre-record a bunch of scenarios (and by that, I mean ENOUGH to give the player the illusion they are actually running a physics simulation), randomly pick one, and use that random ID as our way to identify a particular scenario, that means we'll need to embed tons of data in the game - that could be otherwise saved if the physics engine was deterministic.
And just to check-off anything I've already tried in Nape:
The ball is reset to the same position & rotation at the beginning of the game.
The ball's initial velocity is set on user click, therefore this should override any velocity that carried-over from the last round.
The pegs don't move (they are static), so no point of resetting those.
The part that catches the ball consists of only static boxes and sensors, so no point in resetting those either.
The Citrus Engine provide a similar functionality with the TimeShifter you can check it running the demo Braid (pressing [SHIFT] to back in time), the TimeShifter API

How to avoid tight coupling?

I have been trying to get my head around this problem for the last week and can't seem to find a solution that doesn't either require a singleton or tight coupling.
I am developing a 3D space game, an early demo of which is here...
www.sugarspook.com/darkmatters/demo.html
... and I'm getting to the point of adding Missions which the player will be able to select from the heads up display (Hud class).
The structure of the game is:
The Game class contains the Hud and the ObjectsList class.
The ObjectsList class contains various game Objects, including the Player, the various kinds of ship, planets, and Orbitals (space stations).
Missions get instantiated when the Player gets to within a certain distance of an Orbital.
Missions are added to a MissionsList class, itself within the ObjectsList.
Missions can become unavailable and expire without warning (as if they are selected by another pilot) so the list displayed on the Hud is dynamic and updated regularly.
Previously I've had the Missions dispatching events up to Game which in turn informs Hud of the change. This seems a little clunky to me, as there are various deeper 'levels' to the Hud that the information needs to be passed down to. I end up with a lot of the same functions all the way down the chain.
The solution I was thinking of involved injecting a reference to the MissionsList class into the Hud, enabling it to listen for updates from the Missonslist. I've heard that it's bad practise to mix the state of something with its display, but I don't see how else to get the 'live' list of Missions to the Hud. In contrast, if the Hud contains only display details without reference to the Mission object that generated those details, when a player selects a Mission from the Hud how can I determine which Mission has been chosen?
Is tight coupling in this case OK? Or should I use a singleton to communicate to the Hud?
If there is something fundamentally wrong with anything I'm suggesting I welcome being told what that is and what is the best solution.
Thanks.
Well the simple answer is why not couple via an intermediate interface?
interface IMissionList
{
ObservableCollection<IMission> Missions{get;}
}
Then in your Dependency Injection bind that to something that can resolve to a instance, singleton or constant or etc...
then inject it into your Hud's constructor
Hud(IMissionList missionList){}
Now you are loosely coupled to a contract, the implementation of-which can be changed at any point, so long as the implementation adheres to the contract. Also, due to injection your Hud only has to concern it self with using IMissionList rather than also finding it.
[Edit] Sorry, this is C#, but hopefully the idea is of use. See for actionscript interfaces and Dependency Injection for Actionscript

Who should a method belong to?

I'm trying to design a simple game ---Pong, Arkanoid--- using strictly "Proper OO", whatever that means.
So, by designing myself to death, I'm trying to get to a point where I'll know what to do or not do next time...
Who should handle, for example, colissions? And scorekeeping?
My first idea was giving a couple jobs to the ball, but that started expanding exponentially into a god object: The ball'd know where it is, who it crashed into, and report to the scorekeeping objects.
And that's too much for the poor ball.
rule of thumb:
if an object logically owns all of the state involved, then it owns the methods that use that state
if a method requires state from more than one object:
if a container object owns all of the objects used by the method, then it owns the method, too
otherwise you need a 'bridge' object to own the utility method
unless there is a strong argument for one object to be the 'controller' for the method (can't think of an example offhand though)
in your case, the 'gameboard' or 'game environment' would probably have a 'game physics' class (or group of methods) that owned the collision-detection (utility/bridge) methods
A good or bad design reveals itself by how well it accomodates unexpected requirements, so I would suggest keeping a stock of potential "game features" handy to inform your design reflexions. Since you're doing this as a learning project you can afford to go crazy.
Arkanoid is a very good choice for this, it offers so many options. Make different bricks score different amounts of points. Make some bricks change the score of other bricks when hit. Make some bricks require multiple hits. Give superpowers to the ball, paddle, or bricks. Vary these powers: one of them makes the ball keyboard-controllable, another makes it transparent, another reverses "gravity", and so on. Make bricks drop objects.
The goal is that when you make such a change, it impacts the minimum possible number of classes and methods. Get a feel for how your design must change to fit this criterion.
Use an IDE that has a Refactoring menu, in particular the move method refactoring. (If you haven't, read the book Refactoring.) Experiment with placing your various methods here and there. Notice what becomes hard to change when the method is placed "wrong", and what becomes easier when you place it elsewhere. Methods are placed right when objects take care of their own state; you can "tell" an object to do something, rather than "ask" it questions about its state and then make decisions based on its answers.
Let's assume that in your design each sprite is an object instance. (You could choose other strategies.) Generally, motion alters the state of a sprite, so the method that describes motion for a particular kind of sprite probably belongs on that sprite's class.
Collision detection is a sensitive part of the code, as it potentially involves checking all possible pairs of sprites. You'll want to distinguish checking for collisions and informing objects of collisions. Your ball object needs to alter its motion on colliding with the paddle, for instance. But the algorithm for detecting collisions in general won't belong on the ball class, since other pairs of objects may collide with consequences that matter to the game.
And so on...
Keep in mind that objects can also exist for logical elements of a given problem (not only real elements, like balls and boards).
So for collision detection, you could have a CollidingElement class that handles the position and shape states. This object can then be embedded by composition in any object that should collide in the game and delegate any needed method call to it.
It really depends on your implementation, but I imagine you'd have a "gameboard" object to manage score keeping, or maybe a goal object on each side. As far as collisions I think you might want to pass events between the objects. I think any object should know its location though.
in most games you have statics and actors . .. actors move around and each of them independently figures out when they collide with something since they are aware of their shape and extents

OO Design, open/closed principle question

I've been thinking about this object oriented design question for a while now and have unable to come up with a satisfactory solution, so thought I'd throw it open to the crowds here for some opinions.
I have a Game class that represents a turn based board game, we can assume it's similar to Monopoly for the purposes of this question.
In my design I have a Player class containing a method TakeTurn.
The Game loops through all Players and calls the TakeTurn method to do all the necessary things to complete the turn.
I want to be able to have n number of players, and be able to set an arbitrary number of them to be computer players.
So, my thought was to have a HumanPlayer class and a ComputerPlayer class, both of which derive from Player.
The Game knows only the Player class and simply calls the TakeTurn method on each Player in turn.
My problem comes in the fact that ComputerPlayer objects can be completely automated, i.e. keeping with the Monopoly example, can decide to buy a property using some piece of logic.
Now, with the HumanPlayer object, it needs to get an input from the actual user to be able to buy a property for instance, which seems to imply a different interface and potentially mean they shouldn't derive
I haven't been able to come up with a good solution to the problem without having the Game class know the actual implementations of the various Player classes explicitly.
I could always make the assumption in the Game class that there will only ever be human and computer players and effectively close it for extension, but it doesn't seem like good OO programming.
Any opinions on this would be appreciated.
I think you should not let the Game class handle IO.
this way, the (blocking) TakeTurn method will hide from the game board the means of implementation. it can use other objects to communicate with the user.
All the Game class should concern itself with is the state of the board and the turn. the players should all implement a single Player interface, and hide all implementation from the Game.
If the Game is managing the game state and doing I/O, the Game is doing too much.
You want Game to be tightly focused on just rules and turns and state changes.
Game doesn't know what a player is; it only knows that it has players.
You want Players to examine the Game state and execute the legal actions during their turns.
Human Players and the Game as a whole both share a common I/O package that shows game state and prompts humans for their input.
You can make good use of the Java Observable by making the I/O package an Observer of the Game. That way, Game state changes are reported to the I/O for display or logging or both.
I would probably not have two HumanPlayer and ComputerPlayer classes, but a single Player class which is configured at creation time with the proper input strategy.
The way the player obtains information to decide its move in the next turn of the game is the only thing that varies (from the original problem description, at least), so just encapsulate that in a separate abstraction.
Whatever high-level class that sets up the game should also create the two sets of players (one human, another computer-simulated), with the proper input strategy for each, and then simply give these player objects to the game object. The Game class will then only call the TakeTurn method on the given list of players, for each new turn.
Instead of telling the game class there is only ever one human, why not let it get that input during the menu/initialization of the game? If there are more players, that can be decided via some form of input (select players in the menu), prior to the game class initialization.
The interface that Player presents to Game is orthogonal to the behaviour of derived Player classes.
The fact that the implementation of TakeTurn varies depending on the concrete type of the Player object should not be a cause for concern.
I think the Game Class should not concern about any implementations of the Player classes, and also ignore the User Interface.
Any user input needs to be handled by the HumanPlayer class.
I'd say, the Game class shouldn't care if this is a computer player or a human player. It should always call TakeTurn on the next player class. If this is a human player, it is the responsibility of the Player class, to communicate with the user and ask the user what to do. That means it will block till the user made up his mind. As usually UI interaction takes place in the main thread of an application, it is only important that a blocking TakeTurn won't block the application as a whole, otherwise user input cannot be processed while Game waits for TakeTurn.
Instead of the Game class calling TakeTurn on all the players the players should call TakeTurn on the Game class and the Game class should validate if the right player is taking his turn.
This should help solve the User and Computer player problem.
Im am not sure if this is what you want
public abstract class Player
{
int position;
DecisionMaker decisionDependency;
...
public void TakeTurn()
{
position += RollDice();
GameOption option GetOptions(position);
MakeDescion(option);
}
protected int RollDice()
{
//do something to get the movement
}
protected abstract void MakeDecision(GameOption option);
}
Public class ComputerPlayer : Player
{
public ComputerPlayer()
{
decisionDependency = new AIDecisionMaker();
}
protected override void void MakeDecision(GameOption option)
{
decisionDependency.MakeDecision(option);
//do stuff, probably delgate toan AI based dependency
}
}
Public class HumanPlayer : Player
{
public HumanPlayer()
{
decisionDependency = new UIDecisionMaker();
}
protected override void void MakeDecision(GameOption option)
{
decisionDependency.MakeDecision(option);
//do stuff, probably interacting with the a UI or delgate to a dependency
}
}