Skip to main content
Robb Nemo
Inspiring
January 13, 2025
Question

Remove spawned instances of a drag and drop symbol

  • January 13, 2025
  • 1 reply
  • 170 views

I previously posted a question about how to generate multiple instances of a drag and drop symbol on demand (see thread here) and the solution provided worked incredibly well.

Basically, I wanted to drag and drop symbols onto a map and have the dragged symbol re-spawned so the symbol could be used multiple/indefinite amounts of times.

The solution provided, with the spawning of symbols when I drag them onto the map area, was exactly what I wanted - however, If I drag a symbol onto the map area by mistake, I can't remove the symbol. Is there way to drag the symbol off the map to remove it?

This is the code so far, courtesy of  the brilliant JoãoCésar

const root = this;
let spawnedItem;

function main()
{
	createjs.Touch.enable(stage);
	stage.mouseMoveOutside = true;
	root.stop();
	root.menu.children.forEach(child => child.mouseChildren = false);
	root.menu.on("mousedown", menuDown);
	root.menu.on("pressmove", menuMove);
	root.menu.on("pressup", menuUp);
	root.map.on("mousedown", mapDown);
	root.map.on("pressmove", mapMove);
}

function menuDown(e)
{	
	spawnedItem = new e.target.constructor();
	spawnedItem.x = e.currentTarget.x + e.target.x;
	spawnedItem.y = e.currentTarget.y + e.target.y;
	spawnedItem.mouseChildren = false;
	root.addChild(spawnedItem);
	setDrag(spawnedItem);
}

function menuMove()
{
	drag(spawnedItem);
}

function menuUp(e)
{
	var dropPoint = { x: spawnedItem.x, y: spawnedItem.y };

	if (root.mapRec.hitTest(dropPoint.x - root.mapRec.x, dropPoint.y - root.mapRec.y))
	{
		root.map.addChild(spawnedItem);
		spawnedItem.x = dropPoint.x - root.map.x;
		spawnedItem.y = dropPoint.y - root.map.y;
	}
	else
		root.removeChild(spawnedItem);
	
	spawnedItem = null;
}

function mapDown(e)
{
	setDrag(e.target);
}

function mapMove(e)
{
	drag(e.target, root.mapRec.nominalBounds);
}

function setDrag(target)
{
	target.offset =
	{
		x: stage.mouseX / stage.scaleX - target.x,
		y: stage.mouseY / stage.scaleY - target.y
	};
}

function drag(target, dragArea)
{
	target.x = stage.mouseX / stage.scaleX - target.offset.x;
	target.y = stage.mouseY / stage.scaleY - target.offset.y;
		
	if (dragArea)
	{
		target.x = clamp(dragArea.x, target.x, dragArea.x + dragArea.width);
		target.y = clamp(dragArea.y, target.y, dragArea.y + dragArea.height);
	}
}

function clamp(min, value, max)
{
	if (value < min)
		return min;
	
	if (value > max)
		return max;
	
	return value;
}

main();

  

    1 reply

    kglad
    Community Expert
    Community Expert
    January 13, 2025

    just remove the object:

     

    furnction removeF(obj){

    if(obj.parent){

    obj.parent.removeChild(obj);

    }

    }