actionscript-3flashcollisioninventorycs4

Flash CS4 How do you set variable to the Object Dragging Collison?


I am doing a game for my computer science class and I am working on inventory, dragging an item into it. I do not know how to set the item as whatever the user clicked to drag.

At the moment I hard coded it to the item they are dragging, but in the future I want more items, so a variable set to the item they are dragging would make it work perfectly, but I don't know what it's called to do that.

Here is my code for inventory item dragging

function dragItem (event:MouseEvent):void
{
    knife_loot.startDrag();
}

function dropItem (event:MouseEvent):void
{
    knife_loot.stopDrag();

    if ((knife_loot.hitTestObject(inv_game)) && (inv_game.visible == true))
    {
        trace("Item dropped in inventory")
        trace("")

        knife_loot.x = 80
        knife_loot.y = 120
    }
}

// end of dragging and dropping items

Solution

  • You can start with:

    // List the items you want to drag.
    var aList:Array = [knife_loot, spoon_loot, fork_loot];
    
    // InteractiveObject is superclass for SimpleButton, Sprite and MovieClip.
    // If you're sure what they all are then just use their class instead.
    for each (var anItem:InteractiveObject in aList)
    {
        // Subscribe them all for dragging.
        anItem.addEventListener(MouseEvent.MOUSE_DOWN, onDrag);
    }
    
    public var draggedItem:InteractiveObject;
    
    function onDrag(e:MouseEvent):void
    {
        // Use e.currentTarget because original MouseEvent e.target
        // could be something from deep inside of top object e.currentTarget.
        draggedItem = e.currentTarget as InteractiveObject;
        draggedItem.startDrag();
    
        // Let's hook drop events.
        stage.addEventListener(Event.MOUSE_LEAVE, onDrop);
        stage.addEventListener(MouseEvent.MOUSE_UP, onDrop);
    }
    
    function onDrop(e:Event):void
    {
        // Unhook drop events.
        stage.removeEventListener(Event.MOUSE_LEAVE, onDrop);
        stage.removeEventListener(MouseEvent.MOUSE_UP, onDrop);
    
        // Drop the item.
        draggedItem.stopDrag();
    
        if ((draggedItem.hitTestObject(inv_game)) && (inv_game.visible == true))
        {
            trace("Item", draggedItem.name, "was dropped to inventory.");
            trace("");
    
            draggedItem.x = 80;
            draggedItem.y = 120;
        }
    
        // Forget the item.
        draggedItem = null;
    }