HaxeFlixel Logo HaxeFlixel Snippets
  • About
  • Tutorials
  • Back to HaxeFlixel.com
  • Basics
    • Screen
    • Adding
  • Objects
    • Alive
    • Health
  • Sprites
    • Making Sprites
    • Loading Sprites
    • Animation
    • Alpha
    • Color
    • Facing
    • Scale
    • Baked Rotations
  • Text
    • FlxText
    • FlxBitmapText
  • Movement
    • Velocity
    • Acceleration
    • MaxVelocity
    • Gravity
    • Jumping
    • Angle
    • Angular Velocity
    • Angular Acceleration
  • Groups
    • Basic Group
    • Typed Group
    • Recycling
  • Tiling
    • Tileblock
    • Tilemap
  • Overlap
    • Simple Overlap
    • Overlap Callbacks
  • Collision
    • 1-to-1 Collision
    • Immovable
    • Tilemap Collision
    • Moving Platforms
  • Camera
    • Flash
    • Fade
    • Shake
    • Follow
  • Input
    • Basics
    • Keyboard
    • Mouse
    • Button
  • Sound
    • FlxSound

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

source/PlayState.hx

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()
    {
        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;
    }
}
View Source on GitHub

See Also

  • Movement/Velocity

Tags

collision
  1. Home
  2. Collision
  3. 1-to-1 Collision
Powered By HaxeFlixel Logo HaxeFlixel