HaxeFlixel/flixel-addons

FlxExtendedSprite lock sprites together for mouse drag

NQNStudios opened this issue · 2 comments

I've got 2 projects where I want to be able to click and drag more than one FlxExtendedSprite at the same time. (In one case, it's rectangle-based selection where the player can highlight multiple sprites and they all drag relative to each other. In the other case, there are jigsaw puzzle pieces that snap together and need to drag as one unit after they're connected.)

My current implementation of this is kind of like so:

var lastDragPosition:FlxPoint = null;
var connectedSprites:Array<FlxExtendedSprite> = [];

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

    if (FlxMouseControl.dragTarget != null) {
        if (lastDragPosition != null) {
            var deltaPos = FlxMouseControl.dragTarget.getScreenPosition().subtract(lastDragPosition);
            for (s in connectedSprites) {
                s.x += deltaPos.x;
                s.y += deltaPos.y;
            }
        }
        lastDragPosition = new FlxMouseControl.dragTarget.getScreenPosition();
    }
}

This works, but the connected sprites lag behind the drag target:

Animation

I think this is because super.update() draws all the sprites after updating the drag target, but my own logic happens after the draw call, so the connected sprites are a frame behind.

A possible work-around for me would be to extend FlxExtendedSprite to store and update its own connected sprites, but I wonder if this functionality would be useful to more people, and I should contribute it upstream to FlxExtendedSprite itself.

I think this is because super.update() draws all the sprites after updating the drag target, but my own logic happens after the draw call, so the connected sprites are a frame behind.

FYI all objects get drawn at once and updated at once. You'll never have some objects drawing while others are updating, or anything like that.

The problem here seems to be update order entirely. where is the above code, and where is the code moving the dragged sprite? My guess is that the dragged sprite moves after lastDragPosition is set but before super.update().

Edit: I'm also not sure if getScreenPosition is right here, you probably want to use it's world position, since it works with any zoom and requires less calculations. since your using it to change the world position of the connected sprites

I was able to figure this out by writing my own extended sprite class. Thanks!