Thursday, March 15, 2012

Flash (ActionScript 3) Mouse Click event on the stage using a class

It's been ages since I have used Actionscript (or really done much programming at all). Today I set myself the task of simply creating an event handler for the stage by using a class. Nothing seemed to be working correctly, until it all suddenly seemed to be obvious. 


 I have made the event handler (click_handler) display the X and Y co-ordinates of the screen. Replace this with whatever you want to happen when the screen is clicked. 


Don't know how to use classes at all? Or just need reminding how to declare the main document class (like I did), theres a simple tutorial at Active Tuts to help you out. 


 The Code:

package 
{
import flash.display.MovieClip;

import flash.events.MouseEvent; //Required to allow Mouse Events to be used
import flash.events.Event; //Required to allow the creation of the listener
import flash.display.Stage; //Required to allow 'stage' to be referenced
   
public class main extends MovieClip  
{

  public function main()
  {
  loaderInfo.addEventListener(Event.INIT, createListener); //adds the event listener as the class is loaded 
  }
  
  private function createListener(event:Event):void
  {
  stage.addEventListener(MouseEvent.CLICK, click_handler);  //creates an event handler called "click_handler" (see below) that is connected to the stage.
  }
  
  function click_handler(event:MouseEvent):void //this function is called every time the stage is clicked
  {
  trace("X: " + event.target.mouseX + ", Y: " + event.target.mouseY); //Displays the X and Y position of where the mouse clicked on the stage
  
  }   
  
}

}
   

No comments: