Today, we’re doing collisions in Flixel and how you’d set it up using groups. This is powerful, because it allows us to create collision detection logic consistently in the engine on several objects. Want to know how? Let’s get into it.
FlxGroups are a class in Flixel that allows us to group together objects in the game. You can group sprites, objects, and more for whatever you need. Additionally, you can perform logic on members of the group as well. You can think of it as a more complex array. You can cap the members of the group, perform object pooling, and more. But, how does this help us with collisions?
Collisions are a fundamental part of any game. They are required to interact with objects in the game. For example, talking to an NPC, making sure your players don’t walk out of bounds. All of these examples require some form of detection. We need to know when A overlaps B. Let’s take the NPC example and make it concrete. NPCs are a type of element in the game that requires some form of consistency in their interaction. How would we set this up for multiple NPCs? That’s where groups come in.
Flixel Grouping Example
To do this in Flixel, we’d create a FlxGroup for our NPC class. Once we create the group, we would add our NPCs to this group, allowing us to set up the same rules for NPCs. One of the advantages to Haxe, because it has a robust type system, we can restrict what kind of elements can go into our groups. This makes sure we can only add NPCs to the group. Here’s an example of what it would look like in your code.
As you can see the amount of code required is minimal to achieve your required effect. Now every time the player interacts with an NPC, the behavior will be consistent. You can even see an example of what happens if the player interacts with an enemy as well. Now, there are more uses for FlxGroups, which you’ll see in tutorials coming out soon!
With that said, good luck game making!!