Pages

Friday, November 18, 2011

Animated circle using if condition.

The conditional statement allows you to test a condition and execute a block of code if that condition exists, or execute an alternative block of code if the condition does not exist.

In this post, I will show you how to create a moving ball animation (and it should not exit the stage area) using the if condition. This technique you will get useful when you are creating game.

Final Preview:


Create a new Action script 3 document(width-475, height-250) from the flash welcome screen. After creating the new file. Open the action panel from window menu. You can use the shortcut key F9 from your keyboard. In side your action panel copy and paste the following code and test the movie, you will find out some animated circle.

Action script code:

import flash.display.Sprite;

var myArray:Array=[];
var xVel:Number=5;
var yVel:Number=5;
var myBall:Sprite;

for (var i:Number = 0; i < 75; i++) { myBall = new Sprite(); myBall.graphics.beginFill(Math.random() * 0xffffff, 1); myBall.graphics.drawCircle(0, 0, 2 + Math.random() * 20); myBall.graphics.endFill(); myBall.x= 100 + (Math.random()*(stage.stageWidth-200)); myBall.y= 100 + (Math.random()*(stage.stageHeight-200)); addChild(myBall); var ballObj:Object = new Object(); ballObj.ball=myBall; ballObj.xVal=2+Math.random()*8; ballObj.yVal=2+Math.random()*8; myArray.push(ballObj); } this.addEventListener(Event.ENTER_FRAME, onEnter); function onEnter(event:Event):void { for (var i:Number = 0; i < myArray.length; i++) { myArray[i].ball.x+=myArray[i].xVal; myArray[i].ball.y+=myArray[i].yVal; if (myArray[i].ball.x>=stage.stageWidth-myArray[i].ball.width/2||myArray[i].ball.x<0+myArray[i].ball.width/2) { myArray[i].xVal=- myArray[i].xVal; } if (myArray[i].ball.y>=stage.stageHeight-myArray[i].ball.height/2||myArray[i].ball.y<0+myArray[i].ball.height/2) {
myArray[i].yVal=- myArray[i].yVal;
}
}
}

0 comments:

Post a Comment