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

Distance

FlxMath offers several helper functions check the distance between an object and a {$ flixel.math.FlxPoint %}, the mouse, a touch, or another object.

Use distanceToMouse, distanceToPoint, distanceToTouch, and distanceBetween to get the distance in pixels between your object and the relevant item.

// get the distance between your target and a FlxPoint
distance = FlxVelocity.distanceToPoint(target, point);
Note: Use the related `isDistanceTo*Within` functions if you just want to check if the distance is within a specific value. These functions avoid the expensive `Math.sqrt` call that is used in the other functions.

Demonstration

Source

View Source on GitHub

package;

import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.math.FlxMath;

class PlayState extends FlxState
{
	var sprite:FlxSprite;
	var box:FlxSprite;
	var inRange:Bool;

	override public function create()
	{
		bgColor = 0;

		super.create();

		box = new FlxSprite("assets/bigbox.png");
		box.centerOrigin();
		box.screenCenter();
		add(box);

		sprite = new FlxSprite("assets/sprite.png");
		sprite.centerOrigin();
		sprite.y = FlxG.height / 2 - sprite.height / 2;
		sprite.velocity.x = 100;
		add(sprite);
	}

	override public function update(elapsed:Float)
	{
		if ((sprite.velocity.x > 0 && sprite.x >= FlxG.width - sprite.width)
			|| (sprite.velocity.x < 0 && sprite.x <= 0))
		{
			sprite.velocity.x *= -1;
		}

		inRange = false;
		inRange = FlxMath.isDistanceWithin(sprite, box, 100);
		box.alpha = inRange ? 0.5 : 1;

		super.update(elapsed);
	}
}

Tags

distance math utilities
Powered By HaxeFlixel Logo HaxeFlixel