2009年11月2日 星期一

ActionScript 3.0 學習誌-小孩與父母

在AcitonScript 3.0 中,所有視覺物件建立與控制的方法都一樣,

都是使用new Operator(運算子)的方式建立,例如:

上一次提到的,var mySprite:Sprite = new Sprite();

建議文字與影片片段也可以使用類似的方法:

var myTextfield : TextField = new TextField();
var myMovieClip:MovieClip = MovieClip();

建立之後可以調整所建立的物件的動作或者畫圖在裡面,例如我建立了一個mySprite的分鏡我可以在裡面畫圓形,

mySprite.graphics.beginFill(0xff0000);
mySprite.graphics.drawCircle(0,0,40);
mySprite.graphics.endFill();

但是如果只有寫這樣,事實上它無法被看到,


這是因為mySprite就像是個無父母的孩子,父母指的就是舞台,沒有加入mySprite的話就沒辦法看到他。

所以最後還要在加上addChild(mySprite)才可以看到他:

mySprite.graphics.beginFill(0xff0000);
mySprite.graphics.drawCircle(0,0,40);
mySprite.graphics.endFill();
addChild(mySprite);

因此就算定義視覺物件,沒有幫這個視覺物件指定爸媽(或者幫爸媽說這是他的小孩),它也是不會顯示出來的。

另外,當我們定義了一個視覺物件,他只能存在於一個父母,如果把視覺物件定義到另外一個父母(繼父母),

那它就不會在原本的父母上面顯示了:

===========================================================================

package{
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Reparenting extends Sprite{
private var parent1:Sprite;
private var parent2:Sprite;
private var ball:Sprite;
public function Reparenting(){
init();
}
private function init() : void{
parent1 = new Sprite();
addChild(parent1);
parent1.graphics.lineStyle(1,0);
parent1.graphics.drawRect(-50,-50,100,100);
parent1.x = 60;
parent1.y = 60;
parent2 = new Sprite();
addChild(parent2);
parent2.graphics.lineStyle(1,0);
parent2.graphics.drawRect(-50,-50,100,100);
parent2.x = 170;
parent2.y = 60;
ball = new Sprite();
parent1.addChild(ball);
ball.graphics.beginFill(0xff0000)
ball.graphics.drawCircle(0,0,40);
ball.graphics.endFill();
ball.addEventListener(MouseEvent.CLICK,onBallClick);
}
public function onBallClick(event:MouseEvent):void
{
parent2.addChild(ball)
}
}
}
===========================================================================
上面的程式碼是在說,我建立了parent1,parent2以及ball的分鏡

而ball是建立在parent1分鏡上的(parent1.addChild(ball);),而當我按下了ball,ball的屬性就改成建立在parent2上了(parent2.addChild(ball)),

而當我這樣做的時候,原本在parent1上的ball就消失了。

總結來說,就是一個物件只能有個父母,不能有多個父母的意思,這個方法很好用,

因為可以保存物件的屬性但卻又可以出現在不同的地方!

沒有留言:

張貼留言