我的迷你游戏在舞台上有4个物体,在游戏完成后,我希望它们都从舞台上移除,让游戏重新开始。
我是这样设置的(去掉了大部分比特)
function mainGame():void {
var theCoin:coin = new coin();
var cupOne:cup = new cup();
var cupTwo:cup = new cup();
var cupThree:cup = new cup();
stage.addChild(theCoin);
trace(theCoin.parent);
stage.addChild(cupOne);
trace(cupOne.parent);
stage.addChild(cupTwo);
trace(cupTwo.parent);
stage.addChild(cupThree);
trace(cupThree.parent);
function prepReset():void
{
cupOne.removeEventListener(MouseEvent.CLICK, liftCup1);
cupTwo.removeEventListener(MouseEvent.CLICK, liftCup2);
cupThree.removeEventListener(MouseEvent.CLICK, liftCup3);
stage.addChild(resetBtn);
resetBtn.addEventListener(MouseEvent.CLICK, resetGame);
}
function resetGame(event:MouseEvent):void
{
stage.removeChild(cupOne);
stage.removeChild(cupTwo);
stage.removeChild(cupThree);
letsgoagain();
}
} // end mainGame
function letsgoagain():void
{
stage.removeChild(resetBtn);
mainGame();
trace("RESET")
}
这一切都工作良好的第一次。一旦它第二次重置,我得到
Game Started
[object Stage]
[object Stage]
[object Stage]
[object Stage]
RESET
[object Stage]
[object Stage]
[object Stage]
[object Stage]
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Function/coinGame/$construct/mainGame/resetGame()[*coinGame.as:147]
Cannot display source code at this location.
父级仍然是Stage,但仍然是Stage。removeChild不是正确的语法?我不明白。Stackoverflow,你能给我指出正确的方向吗?
下面是一个如何设置该类的示例:
public class coinGame extends MovieClip
{
public var theCoin:coin;
public var cupOne:cup;
public var cupTwo:cup;
public var cupThree:cup;
public function coinGame():void
{
initGame();
}
public function initGame():void
{
theCoin = new coin();
cupOne = new cup();
cupTwo = new cup();
cupThree = new cup();
addChild(theCoin);
addChild(cupOne);
addChild(cupTwo);
addChild(cupThree);
}
public function prepReset():void
{
cupOne.removeEventListener(MouseEvent.CLICK, liftCup1);
cupTwo.removeEventListener(MouseEvent.CLICK, liftCup2);
cupThree.removeEventListener(MouseEvent.CLICK, liftCup3);
addChild(resetBtn);
resetBtn.addEventListener(MouseEvent.CLICK, resetGame);
}
public function resetGame(event:MouseEvent):void
{
removeChild(cupOne);
removeChild(cupTwo);
removeChild(cupThree);
letsgoagain();
}
function letsgoagain():void
{
removeChild(resetBtn);
initGame();
}
}
我没有声明你的resetBtn或添加事件监听器等,但这是基本的结构。
将对象的创建和添加到initGame()
方法中,可以让您轻松地重新启动游戏。构造函数只执行一次,因此最好不要将可能需要多次执行的操作放在构造函数中。
另外,除非您想在每次游戏重置时创建杯子,否则您可以这样做:
public function coinGame():void
{
theCoin = new coin();
cupOne = new cup();
cupTwo = new cup();
cupThree = new cup();
initGame();
}
public function initGame():void
{
addChild(theCoin);
addChild(cupOne);
addChild(cupTwo);
addChild(cupThree);
}
这样,您就不必每次都创建这些对象的新实例,而只需根据需要在显示列表中添加/删除它们。这可能是你想要的。