AS3 Keyboard events - actionscript-3

How would one go about adding event listeners for multiple keystrokes, for example if the up and right buttons are pressed player goes diagonally in that direction.

Check out the following code, I store the pressed key in a object and then animated a sprite using the object :
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
private var _keys:Object = { };
private var _sprite:Sprite = new Sprite;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
_sprite.graphics.beginFill(0xff0000, 1);
_sprite.graphics.drawRect(0, 0, 40, 40);
_sprite.graphics.endFill();
_sprite.x = 100;
_sprite.y = 100;
addChild(_sprite);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onKeyDown(e:KeyboardEvent):void
{
_keys[e.keyCode] = true;
}
private function onKeyUp(e:KeyboardEvent):void
{
_keys[e.keyCode] = false;
}
private function onEnterFrame(e:Event):void
{
if (_keys[Keyboard.UP])
{
_sprite.y --;
}
if (_keys[Keyboard.DOWN])
{
_sprite.y ++;
}
if (_keys[Keyboard.RIGHT])
{
_sprite.x++;
}
if (_keys[Keyboard.LEFT])
{
_sprite.x--;
}
}
}
}

Related

Movement Keys not Working

Nothing is happening when I press the arrow keys, but neither are there any errors: what's wrong with this? If I remove the key press testing it accelerates accordingly...
At this stage I am just trying to move a block around a screen in an inertial manner using the arrow keys. However, this is my first foray into AS3 so I may be going about it in completely the wrong manner.
Any help would be greatly appreciated.
Unit.AS:
package {
import flash.display.MovieClip;
import flash.events.*
import flash.ui.Keyboard
public class Unit extends MovieClip {
var velocityX:Number = 1;
var velocityY:Number = 1;
var accellerationX:Number = 1;
var accellerationY:Number = 1;
public function Unit(){
addEventListener("enterFrame", move);
}
private function move(e:Event){
accellerate()
this.x += velocityX;
this.y += velocityY;
}
private function accellerate(){
if (Key.isDown(Keyboard.UP)){
velocityY += accellerationY;
trace("Accellerating");
}
if (Key.isDown(Keyboard.DOWN)){
velocityY -= accellerationY;
trace("Accellerating");
}
if (Key.isDown(Keyboard.RIGHT)){
velocityX += accellerationX;
trace("Accellerating");
}
if (Key.isDown(Keyboard.LEFT)){
velocityX -= accellerationX;
trace("Accellerating");
}
}
}
}
Key.AS:
package
{
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
public class Key {
private static var initialized:Boolean = false;
private static var keysDown:Object = new Object();
public static function initialize(stage:Stage) {
if (!initialized) {
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
stage.addEventListener(Event.DEACTIVATE, clearKeys);
initialized = true;
}
}
public static function isDown(keyCode:uint):Boolean
{
return Boolean(keyCode in keysDown);
}
private static function keyPressed(event:KeyboardEvent):void {
keysDown[event.keyCode] = true;
}
private static function keyReleased(event:KeyboardEvent):void {
if (event.keyCode in keysDown) {
delete keysDown[event.keyCode];
}
}
private static function clearKeys(event:Event):void {
keysDown = new Object();
}
}
}
On your unit constructor function call the initialize(stage) static function.
Key.initialize(stage);

How can I dispatch event to another class in Action Script 3?

I've searched few docs and I couldn't find about dispatching event to another classes.
I'm trying to make like this.
'main' class has button.
'main','sub' class gonna trace "button is clicked" when button is clicked
I can trace that in 'main' class with dispatch event.
but 'sub' class is problem.
how can I dispatch event like that into 'sub' class?
Main class
package com
{
import flash.events.*;
import flash.display.MovieClip;
import com.sub;
public class main extends MovieClip
{
public static const BTN_CLICKED:String = "btn_Clicked";
public function main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
var flashVars:Object = {};
removeEventListener(Event.ADDED_TO_STAGE, init);
if(parent != null && parent.parent != null)
{
flashVars = parent. parent.loaderInfo.parameters;
}
else
{
flashVars = this.root.loaderInfo.parameters;
}
//entry point
var subClass:sub = new sub;
subClass.init();
btn.addEventListener(MouseEvent.CLICK, onClick);
addEventListener(BTN_CLICKED, onbtnClicked, false, 0, true);
}
public function onClick(e:MouseEvent)
{
dispatchEvent(new Event(BTN_CLICKED));
}
public function onbtnClicked(e:Event)
{
trace("clicked");
}
}
}
Sub Class
package com
{
import flash.events.*;
import flash.display.MovieClip;
import com.main;
public class sub extends MovieClip
{
public function sub():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//entry point
trace("sub class loaded");
}
}
}
You should relocate var subClass:sub to the main set of main class definitions, beside public static const BTN_CLICKED:String = "btn_Clicked";. Then, you can do subClass.dispatchEvent(...).
public class main extends MovieClip {
private var subClass:sub;
public function main() {
...
subClass=new sub();
addChild(subClass); // not just "init()", it's wrong
...
}
public function onClick(e:MouseEvent)
{
dispatchEvent(new Event(BTN_CLICKED));
subClass.dispatchEvent(new Event(BTN_CLICKED));
}
}

ActionScript 3.0 - Dispatch event class to class

I'm working in Action Script 3.0 and I have a question in DispatchEvent class.
following code is standalone class.
I want to dispatch event to 'main' class and 'sub' class when event occured.
I'm stuck on this issue. please help me.
package com
{
import flash.events.*;
import flash.display.MovieClip;
import com.sub;
public class main extends MovieClip
{
public static const BTN_CLICKED:String = "btn_Clicked";
public function main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
var flashVars:Object = {};
removeEventListener(Event.ADDED_TO_STAGE, init);
if(parent != null && parent.parent != null)
{
flashVars = parent. parent.loaderInfo.parameters;
}
else
{
flashVars = this.root.loaderInfo.parameters;
}
//entry point
var subClass:sub = new sub;
subClass.init();
btn.addEventListener(MouseEvent.CLICK, onClick);
addEventListener(BTN_CLICKED, onbtnClicked, false, 0, true);
}
public function onClick(e:MouseEvent)
{
dispatchEvent(new Event(BTN_CLICKED));
}
public function onbtnClicked(e:Event)
{
trace("clicked");
}
}
}
and below is 'sub' class.
package com
{
import flash.events.*;
import flash.display.MovieClip;
import com.main;
public class sub extends MovieClip
{
public function sub():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
//entry point
trace("sub class loaded");
}
}
}
yes, there's nothing in 'sub' class... how can I get dispatch event in sub class?

Keep receiving error: access of undefined property menu in AS3

I am following a tutorial (http://flashdeveloptutorial.blogspot.com/2011/08/chapter-2.html) for AS3 using flash develop to create a pong clone and am having trouble with displaying a main menu. I previously had a functioning prototype with a moving paddle so I believe the error(s) is in my revised(or new) Main, MainMenu, PongGame or CustomEvents file(s). When I run the code as instructed through the tutorial I receive the error ; access of undefined property menu in my Main.as file:
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author
*/
public class Main extends Sprite
{
private var game:PongGame;
****private var menu:MainMenu;****
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
}
private function buildMenu():void {
menu = new MainMenu();
addChild(menu);
menu.addEventListener(CustomEvents.LAUNCH_GAME, startGame, false, 0, true);
}
private function startGame(e:CustomEvents):void {
removeChild(menu);
menu.removeEventListener(CustomEvents.LAUNCH_GAME, startGame);
menu = null;
game = new PongGame();
addChild(game);
}
}
}
So I added the "private var menu:MainMenu;" section but I do not know what class/ .as file to reference? or how to define var menu:
Sorry for the large amount of attached code. I did not change paddle.as which is the longest file.
assets.as
package
{
public class Assets
{
[Embed (source = '../lib/paddle.png')] public static const Pad:Class;
public function Assets(): void {
}
}
}
Paddle.as
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
public class Paddle extends Sprite {
private var pic:Bitmap = new Assets.Pad();
public function Paddle():void {
addEventListener(Event.ADDED_TO_STAGE, go);
}
private function die(e:Event):void {
removeChild(pic);
pic = null;
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
removeEventListener(Event.ENTER_FRAME, enterFrame);
removeEventListener(Event.REMOVED_FROM_STAGE, die);
}
private function go(e:Event) : void {
removeEventListener(Event.ADDED_TO_STAGE, go);
addChild(pic);
y = stage.stageHeight - pic.height;
x = stage.stageWidth * .5 - pic.width * .5;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler, false, 0, true);
addEventListener(Event.ENTER_FRAME, enterFrame, false, 0, true);
addEventListener(Event.REMOVED_FROM_STAGE, die);
}
private var movingLeft:Boolean;
private var movingRight:Boolean;
private function enterFrame(e:Event):void {
if (movingLeft) {
if(x-speed >= 0) {
x -= speed;
}
else {
x = 0;
}
}
else if (movingRight) {
if (x + speed + pic.width <= 600) {
x += speed;
}
else {
x = 600 - pic.width;
}
}
}
private var speed:int = 10;
private function keyDownHandler(e:KeyboardEvent):void {
if (e.keyCode == 38 || e.keyCode == 87) {
if (!movingLeft) {
movingLeft = true;
}
}
else if (e.keyCode == 40 || e.keyCode == 83) {
if (!movingRight) {
movingRight = true;
}
}
}
private function keyUpHandler(e:KeyboardEvent):void {
if (e.keyCode == 38 || e.keyCode == 87) {
if (movingLeft) {
movingLeft = false;
}
}
if (e.keyCode == 40 || e.keyCode == 83) {
if (movingRight) {
movingRight = false;
}
}
}
}
}
mainmenu.as
package
{
import flash.events.Event;
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.MouseEvent;
public class MainMenu extends Sprite
{
private var pongButton:Sprite;
public function MainMenu():void{
addEventListener(Event.ADDED_TO_STAGE, go);
}
private function go(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, go);
pongButton = item("Play", 20, 30, launchGame, 0xFF0000);
addChild(pongButton);
}
private function launchGame(e:MouseEvent):void {
dispatchEvent(new CustomEvents(CustomEvents.LAUNCH_GAME));
}
private function item(buttonText:String, X:int, Y:int, Funct:Function, txtColor:uint = 0xFFFFFF):Sprite {
var item:Sprite = new Sprite();
item.graphics.beginFill(0);
item.graphics.lineStyle(1, txtColor, .5);
item.graphics.drawRect(0, 0, 250, 30);
var myText:TextField = new TextField();
myText.selectable = false;
myText.width = 250;
myText.height = 30;
item.addChild(myText);
myText.autoSize = "center";
myText.text = buttonText;
myText.textColor = txtColor;
item.addEventListener(MouseEvent.CLICK, Funct);
item.x = X;
item.y = Y;
return item;
}
}
}
PongGame.as
package
{
import flash.display.Sprite;
import flash.events.Event;
public class PongGame extends Sprite
{
private var paddle:Paddle;
public function PongGame():void {
addEventListener(Event.ADDED_TO_STAGE, go);
}
private function go(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, go);
paddle = new Paddle();
addChild(paddle);
}
}
}
CustomEvents.as
package
{
import flash.events.Event;
public class CustomEvents extends Event
{
public static const LAUNCH_GAME:String = "launch_game";
public function CustomEvents(e:String):void {
super(e);
}
}
}
I'm not sure where to go from here to fix this error. Any help would be appreciated.
Although you've correctly added the menu property, the menu is never displayed because buildMenu() function is never called.
From your main class init(), call buildMenu() to instantiate and add menu to the stage:
Main.as
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
buildMenu();
}

Audio seek bar control on flash

I have a scenario , I am developing a audio player and want to write code for audio track seek bar.
Any help is appreciated.
Assuming you have a Sound object and a SoundChannel object to play the Sound object, you can do something like this:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var _trackBar:Sprite;
private var _sound:Sound;
private var _soundChannel:SoundChannel;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
_trackBar = new Sprite();
_trackBar.graphics.beginFill(0);
_trackBar.graphics.drawRect(-10, 0, 20, 40);
_trackBar.graphics.endFill();
addChild(_trackBar);
graphics.lineStyle(2);
graphics.moveTo(_trackBar.x - 10, _trackBar.y);
graphics.lineTo(_trackBar.x - 10, _trackBar.y +_trackBar.height);
graphics.moveTo(_trackBar.x + 200, _trackBar.y);
graphics.lineTo(_trackBar.x + 200, _trackBar.y + _trackBar.height);
_sound = new Sound();
_sound.addEventListener(Event.COMPLETE, onLoaded);
_sound.load(new URLRequest("[mp3 url goes here].mp3"));
}
private function onLoaded(e:Event):void
{
_soundChannel = _sound.play();
stage.addEventListener(Event.ENTER_FRAME, onTick);
_trackBar.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
_trackBar.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
private function onTick(e:Event):void
{
if (!_soundChannel)
{
return;
}
_trackBar.x = 200 * (_soundChannel.position / _sound.length);
}
private function onMouseUp(e:MouseEvent):void
{
_trackBar.stopDrag();
_soundChannel = _sound.play(_sound.length * (_trackBar.x / 200));
}
private function onMouseDown(e:MouseEvent):void
{
_soundChannel.stop();
_soundChannel = null;
_trackBar.startDrag(false, new Rectangle(0, 0, 200, 0));
}
}
}
Please note: this is very rough and can definitely be optimized. It's just something thrown together to show you how you would accomplish such a task.