Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
HaxeFlixel collision detection with groups example.
import flixel.FlxState;
import flixel.FlxSprite;
import flixel.FlxG;
import flixel.util.FlxColor;
class PlayState extends FlxState {
//Creating the player, enemies, and npc group.
public var npcs:FlxTypedGroup<FlxSprite>;
public var enemies:FlxTypedGroup<FlxSprite>;
public var player:FlxSprite;
override public function create() {
//Create Player
player = new FlxSprite(30, 30);
player.makeGraphic(16, 16, FlxColor.WHITE);
//Initialize enemies
enemies = new FlxTypedGroup<FlxSprite>();
//Initialize NPC Group and add it to the scene for players to view and interact with
npcs = new FlxTypedGroup<FlxSprite>();
//Create enemies and Npcs
public function createEnemies() {
var enemy = new FlxSprite(50, 50);
public function createNpcs() {
var npc = new FlxSprite(80, 80);
override public function update(elapsed:Float) {
//Whenever the player overlaps with the an npc in the npcs Group, the playerInteractWithNpc function will run.
FlxG.overlap(player, npcs, playerInteractWithNpc);
//Whenever the player overlaps with an enemy he should take damage.
FlxG.overlap(player, enemies, playerTouchEnemy);
//Handler function to run whenever the player overlaps with the npc
public function playerInteractWithNpc(player:FlxSprite, npc:FlxSprite) {
//If the player hits Z when overlapping with the NPC this will trigger a message in the log.
if(FlxG.keys.anyJustPressed([Z])) {
trace('Interacted with the Npc in the game.');
public function playerTouchEnemy(player:FlxSprite, enemy:FlxSprite) {
//Player takes damage 1;

This comment has been minimized.

Copy link
Owner Author

@KinoAR KinoAR commented Mar 26, 2021

Quick Notes

There is more code required if you want the player to move around and what not, but this is essentially how you would set up the interactions between you the player, and the NPCs in your game.

Then you can program the logic around what each NPC should be allowed to do and so on.
This approach can also be used for enemies and other large groups in your game to create consistency with how the player expects the game's rules to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment