So basically I've got a MovieClip called Jug and when the egg is clicked and dragged to the Jug I want it to disappear and then re-add itself in the place it first started. Aswell as this I want a variable to be added by 1 in value.
I have tried fiddling around with this for a while now and I can't figure it out since when I remove child it gets errors. Here's the code:
var eggClickOffset:Point = null;
var egg:Egg = new Egg();
egg.x = 290;
egg.y = 330;
addChild(egg);
var eggAmount:TextField = new TextField();
eggAmount.defaultTextFormat = textFormat;
eggAmount.x = 250;
eggAmount.y = 60;
eggAmount.height = 18;
eggAmount.width = 100;
eggAmount.border = true;
eggAmount.text = "Incorrect Amount";
eggAmount.background = true;
eggAmount.backgroundColor = 0xff0000;
stage.focus = eggAmount;
addChild(eggAmount);
var eggs:int;
eggs = 0;
//Egg Event listeners:
egg.addEventListener(Event.ENTER_FRAME, eggAmountCounter);
egg.addEventListener(MouseEvent.MOUSE_DOWN, startEggDrag);
egg.addEventListener(MouseEvent.MOUSE_UP, stopEggDrag);
egg.addEventListener(Event.ENTER_FRAME, dragEgg);
egg.addEventListener(Event.ENTER_FRAME, checkEggCollision);
//starting egg drag:
function startEggDrag(event:MouseEvent):void
{
eggClickOffset = new Point(event.localX,event.localY);
}
//Stopping the egg drag:
function stopEggDrag(event:MouseEvent):void
{
eggClickOffset = null;
}
//Egg Dragging:
function dragEgg(event:Event):void
{
if (eggClickOffset != null)
{// must be dragging
egg.x = mouseX - eggClickOffset.x;
egg.y = mouseY - eggClickOffset.y;
}
}
//When egg hits jug:
function checkEggCollision(event:Event):void
{
if (jug.hitTestObject(egg))
{
eggs + 1;
egg.removeEventListener(MouseEvent.MOUSE_DOWN, startEggDrag);
egg.removeEventListener(Event.ENTER_FRAME, dragEgg);
removeChild(egg);
addChild(egg);
egg.x = 300;
egg.y = 300;
}
}
//How many eggs:
function eggAmountCounter(event:Event):void {
if(eggs == 3){
eggAmount.text = "Corrent Amount";
}
}
So adding and removing things from containers is actually quite expensive in terms of what the toolkit has to do to redraw itself. And there is usually problems like this you encounter where it just doesn't work as advertised. So my suggestion to you is never add/remove components when you want to control visibility. Simply mark them visible=false/true, and optionally remember to use includeInLayout=true/false. Since you have movie clips visible=true/false should be good enough.
If you just want the egg to start back at its original position just simply modify its x,y location directly. I'd create a simple method that takes in an egg and sets all of the properties for the initial state. In your stopEggDrag method simply call that function passing the egg that was being drug on the screen. Viola it pops back to where it was.
The trick here is that you don't have to solve the remove problem if you never remove the object.