Pages

Saturday, February 18, 2012

Mouse Event and Drawing API : A simple colorful application.

Events are responsibility for to do certain things. There are many Events inside AS 3. Like Mouse Event, Keyboard Event, Timer Event, Text Event and so many others.

Preview:



In this post we will do some experiment with Mouse Event. Because this Event is very simple and straightforward. When we use our mouse there are many parameters are associate with it, Like, CLICK, MOUSE_OVER, MOUSE_OUT, MOUSE_DOWN, MOUSE_UP and so many others. If you want more information about Event, then feel free to visit this link.

Before move ahead, I will give you the details of our project setup, so, you will get the same result at the end.

Create a folder any where in your hard drive, name it what ever you want. Then launch the flash SDK and create two files, one is Flash File (Action script 3.0) and another is ActionScript File.


After create the file save both file inside the folder, which one you created few minutes back. I am giving the flash file name "event" and for the class file name "EventTest". Feel free to give more descriptive name for your project. Open the "event" flash file, then go to the property area and the publish section, you will find out similar like this,
You can see a field called class, enter there your class file name. My class file name is EventTest, if your file name is something different enter the same name here.

Now open the class file called EventTest and enter the following code -

package {

import flash.display.Sprite;
import flash.events.MouseEvent;

public class EventTest extends Sprite {

public function EventTest() {
stage.addEventListener(MouseEvent.CLICK, onClick);
}

private function onClick(evt:MouseEvent):void {

var _color:uint = Math.random() * 0xFFFFFF;
var _xPos:Number = Math.random() * stage.stageWidth - 10;
var _yPos:Number = Math.random() * stage.stageHeight - 10;
var _radius:Number = Math.random() * 75 - 25;

var _myShape:Sprite = new Sprite();
_myShape.graphics.beginFill(_color);
_myShape.graphics.drawCircle(_xPos, _yPos, _radius);
_myShape.graphics.endFill();
addChild(_myShape);

}

}
}

Feel free to download the source file for your reference.