Skip to main content
Known Participant
June 15, 2016
Question

How can i add multiple balls?

  • June 15, 2016
  • 2 replies
  • 263 views

var ballSpeedX:int = -9;

var ballSpeedY:int = -12;

init();

function init():void

{

    stage.addEventListener(Event.ENTER_FRAME, loop);

}

function loop(e:Event):void

{

    ball.x += ballSpeedX;

    ball.y += ballSpeedY;

    if(ball.x <= ball.width/2){

        ball.x = ball.width/2;

        ballSpeedX *= -1;

    } else if(ball.x >= stage.stageWidth-ball.width/2){

        ball.x = stage.stageWidth-ball.width/2;

        ballSpeedX *= -1;

    }

  

    if(ball.y <= ball.height/2){

        ball.y = ball.height/2;

        ballSpeedY *= -1;

    } else if(ball.y >= stage.stageHeight-ball.height/2){

        ball.y = stage.stageHeight-ball.height/2;

        ballSpeedY *= -1;

    }

  if(ball.hitTestObject(wall.wallu) || ball.hitTestObject(wall.walld))

  {

  ballSpeedY *= -1;

  }

  if(ball.hitTestObject(wall.walll) || ball.hitTestObject(wall.wallr))

  {

  ballSpeedX *= -1;

  }

}

This topic has been closed for replies.

2 replies

Ned Murphy
Legend
June 15, 2016

If you are adding them manually then just add them and then place their instance names in an array so that you can loop thru the array in your loop function.

kglad
Community Expert
Community Expert
June 15, 2016

var ballNum:int = 10;  // or whatever

var ballSpeedX:int = -9;

var ballSpeedY:int = -12;

var ball:Ball;  // create Ball class

var ballA:Arrray = [];

var i:int;

for(i=0;i<ballNum;i++){

ball=new Ball();

ball.speedX = ballSpeedX*Math.random();  // or whatever if you want them to have different speeds

ball.speedY = ballSpeedY*Math.random();

ball.x=?

ball.y=?

ballA.push(ball);

}

init();

function init():void

{

stage.addEventListener(Event.ENTER_FRAME, loop);

}

function loop(e:Event):void

{

for(i=0;i<ballA.length;i++){

ball=ballA;

ball.x += ballSpeedX;

ball.y += ballSpeedY;

if(ball.x <= ball.width/2){

ball.x = ball.width/2;

ball.speedX *= -1;

} else if(ball.x >= stage.stageWidth-ball.width/2){

ball.x = stage.stageWidth-ball.width/2;

ball.speedX *= -1;

}

if(ball.y <= ball.height/2){

ball.y = ball.height/2;

ball.speedY *= -1;

} else if(ball.y >= stage.stageHeight-ball.height/2){

ball.y = stage.stageHeight-ball.height/2;

ball.speedY *= -1;

}

if(ball.hitTestObject(wall.wallu) || ball.hitTestObject(wall.walld))

{

ball.speedY *= -1;

}

if(ball.hitTestObject(wall.walll) || ball.hitTestObject(wall.wallr))

{

ball.speedX *= -1;

}

}

}