HaxeFlixel Logo HaxeFlixel Snippets
  • About
  • Back to HaxeFlixel.com
    • Screen
    • Adding
    • Alive
    • Health
    • Making Sprites
    • Loading Sprites
    • Animation
    • Alpha
    • Color
    • Facing
    • Scale
    • Baked Rotations
    • FlxText
    • FlxBitmapText
    • Velocity
    • Acceleration
    • MaxVelocity
    • Gravity
    • Jumping
    • Angle
    • Angular Velocity
    • Angular Acceleration
    • Basic Group
    • Typed Group
    • Recycling
    • Sorting
    • Tileblock
    • Tilemap
    • Ray
    • tileProperties
    • Autotiles
    • Simple Overlap
    • Overlap Callbacks
    • 1-to-1 Collision
    • Immovable
    • Tilemap Collision
    • Moving Platforms
    • Flash
    • Fade
    • Shake
    • Follow
    • scrollFactor
    • Basics
    • Keyboard
    • Gamepad
    • Mouse
    • Button
    • FlxSound
    • FlxState
    • FlxSubState
    • Tween
    • Angle
    • Color
    • Motion
    • Num
    • Callbacks
    • FlxTimer
    • FlxSignal
    • moveTowards
    • Distance
    • velocityFromAngle
    • timeScale
    • drawLine

1-to-1 Collision

The simplest form of collision is 1-to-1 collision. You call FlxG.collide(), optionally setting a callback to trigger when collision happens.

// checks if 2 objects collided, and calls the function `callback` if they do
FlxG.collide(objectA, objectB, callback);

Demonstration

Source

View Source on GitHub

package;

import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.util.FlxColor;

class PlayState extends FlxState
{
	var spriteA:FlxSprite;
	var spriteB:FlxSprite;

	override public function create()
	{
		bgColor = 0;

super.create();

		spriteA = new FlxSprite("assets/sprite.png");
		spriteA.x = 24;
		spriteA.y = FlxG.height / 2 - spriteA.height / 2;
		add(spriteA);

		spriteB = new FlxSprite("assets/sprite.png");
		spriteB.x = FlxG.width - 24 - spriteB.width;
		spriteB.y = FlxG.height / 2 - spriteB.height / 2;
		add(spriteB);

		spriteA.velocity.x = 150;
		spriteB.velocity.x = -150;
	}

	override public function update(elapsed:Float)
	{
		super.update(elapsed);

		FlxG.collide(spriteA, spriteB, collision);

		if (spriteA.x <= 0)
			spriteA.velocity.x *= -1;
		if (spriteB.x >= FlxG.width - spriteB.width)
			spriteB.velocity.x *= -1;
	}

	function collision(spriteA:FlxSprite, spriteB:FlxSprite)
	{
		spriteA.velocity.x = -150;
		spriteB.velocity.x = 150;
	}
}

Tags

collision
Powered By HaxeFlixel Logo HaxeFlixel