2009-02-17 226 views
0

我試圖通過使用for循環來創建動態球。 由於某種原因,我得到了兩個物體(跟蹤顯示2個球和他們的不同屬性),但在舞臺上我只能看到最後一個創建的物體。For(循環)動態創建

這是我的代碼:

var randomBall_mc:ball=new ball(); 
for (i=1; i<3; i++) 
{ 
     addChild(randomBall_mc); 
    randomBall_mc.name="randomBall"+i; 
    randomBall_mc.x=150*i; 
    randomBall_mc.y=175; 
    randomBall_mc.height=20*i; 
    randomBall_mc.width=20*i; 
     trace("randomBall"+i); 
    trace(randomBall_mc.x); 
    trace(randomBall_mc.height); 
} 

什麼是錯在我的代碼?

回答

1

var randomBall_mc:ball = new ball();應該是裏面的for循環,以創建多個「球」

for (i=1; i<3; i++) { 
var randomBall_mc:ball=new ball();** 
addChild(randomBall_mc); 
randomBall_mc.name="randomBall"+i; 
randomBall_mc.x=150*i; randomBall_mc.y=175; 
randomBall_mc.height=20*i; 
randomBall_mc.width=20*i; trace("randomBall"+i); 
trace(randomBall_mc.x); 
trace(randomBall_mc.height);} 
1

看起來好像你只是在循環之前實例化一次球,而不是每次迭代都要這樣做。

0

答案是現貨,但拋光碼了一點:

var ball:Ball; // Observe convention: capitalise class names var i:int = 0; // Make sure to type your variables for (; i < 3; i++) { ball = new Ball(); ball.name = "randomBall"+i; ball.x = 150 * i; ball.y = 175; ball.height = 20 * i; ball.width = 20 * i; addChild(ball); // Configure your instance first; // then add it to the display list trace("ball:", i, ball.x, ball.height); }