Search code examples
actionscript-3flashdrag-and-dropcollision-detectiontarget

ActionScript 3. Drag and drop game going wrong


I have flash game written in ActionScript 3, here are 4 items which should be dragged to specific fields, It's working correctly when dragging item to any fields (If correct field - item get field's x, y position and if field is wrong - item returns to his fixed position).

It's going wrong when I'm trying to drop item on other item (for example trying to drag and drop Item1 on Item2), they change positions. If I drag Item1 and It not hitTestObject correct field It should get back to Items1's position, but It going to Item2 x, y position and Item2 to Item1 x, y position.

I'm using following code:

private function getPosition(target:Object):void 
{
    xPos = target.x;
    yPos = target.y;
}
private function dragObject(e:MouseEvent):void
{
    getPosition(e.target);
    e.target.startDrag();
    trace("Started drag");
}
private function stopDragObject(e:MouseEvent):void
{
    if (e.target.hitTestObject(e.currentTarget.parent[field])) {
        e.target.x = (e.currentTarget.parent[field]).x;
        e.target.y = (e.currentTarget.parent[field]).y;
    } else {
        e.target.x = xPos; //here is part where item get's back to his position
        e.target.y = yPos; //seems that here is problem
    }
}

Solution

  • I think this is a depth problem ( index position ) of your items, because, for example, when you drag an item with a depth 1 over another one with index 5, the target of your MouseEvent.MOUSE_UP event will be the second object and not the first, so I think that you can avoid that by setting the index of your current item as the highest in your items container like this :

    function dragObject(e:MouseEvent):void {
    
        var container:DisplayObjectContainer = DisplayObjectContainer(e.target.parent);
            container.setChildIndex(DisplayObject(e.target), container.numChildren - 1);
    
        // other instructions
    
    }
    

    EDIT :

    To avoid your second problem ( positioning the target of MouseEvent.MOUSE_UP event at (0, 0) or under the last dragged object ), you can use a boolean var to indicate if you are dragging an item or not :

    var is_dragging:Boolean = false;
    
    function dragObject(e:MouseEvent):void
    {
        is_dragging = true;
    
        // other instructions
    }
    function stopDragObject(e:MouseEvent):void
    {   
        if(!is_dragging) return;
    
        // other instructions
    
        is_dragging = false;    
    }
    

    The boolean var is just a manner, you can also initialize your xPos and yPos, ...

    Note : To reproduce the problem, you can just click anywhere on your stage and release your mouse over an item, this item will be positioned at (0, 0) because xPos and yPos are undefined, but if you have already dragged an other item, the item be positioned at (xPos, yPos), so under your last dragged item.

    Hope that can help.