KeyboardEvent Help
Okay, I need to know how to use the letter keys, as in
abcdef.. to do simple things like advance a movie clip in
actionscript.. anybody have the code?
there's no "the code". you need to code for the specifics
that you want.
this is the basic code to use during production of your
project:
stage.focus = this;
this.addEventListener(KeyboardEvent.KEY_DOWN, keyDownF;
function keyDownF(e:KeyboardEvent):void {
trace(e.keyCode);
}
Similar Messages
-
Std barcode reader - keyboardevent for stream of chars - help :(
Hi all,
It's the very first time for me in adobe forum so.. hi everyone
I've got a question related to my air application. This application has many controls like textinput button etc. etc.
I would like to catch a barcode (a very fast keyboard stream of chars) in the main application (this isn't a problem I already can do this) and, if it is a barcode then i would like to stop the propagation of the chars otherwise the propagation of the chars continue as usual
In order to catch the stream of chars I've used a timer, restarted every time i retrieve a character, if this timer expire and I have collect more the 5 chars I suppose the chars collected could be a barcode otherwise the chars (if they are less than 5) should be normal character from the user that use a keyboard
the effect is:
first case:
a fast keyboard chars coming (a.. ok this is a barcode)
stops the writing for example in the related textinput that has focus
elaborate the barcode
second case:
a character or two is arrived from the keyboard (ok this isn't a barcode)
continue with propagation and the related textinput show the character
is this possible?
I've tryed it.. but I can't find the solution, could anyone help me?
thank you
edit: if it isn't clear, please let me know, I can try to explain the problem in a better wayI tried to made some other test.
first test -------------
here I tried to record all the 3 events (i report only the script part)
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
import spark.components.Application;
var eventArray:Array = new Array()
var t:Timer = new Timer(5000)
private function init():void
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, appKeyDown, true);
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_UP, appKeyUp, true);
NativeApplication.nativeApplication.addEventListener(TextEvent.TEXT_INPUT, textinput, true);
private function appKeyUp(e:KeyboardEvent):void
trace("appKeyUp")
var evttmp:KeyboardEvent = new KeyboardEvent(KeyboardEvent.KEY_UP)
evttmp = e.clone() as KeyboardEvent
eventArray.push(evttmp);
e.stopPropagation()
e.preventDefault()
private function textinput(e:TextEvent):void
trace("textinput")
var evttmp:TextEvent = new TextEvent(TextEvent.TEXT_INPUT)
evttmp = e.clone() as TextEvent
eventArray.push(evttmp);
e.stopPropagation()
e.preventDefault()
private function appKeyDown(e:KeyboardEvent):void
trace("appKeyDown")
var evttmp:KeyboardEvent = new KeyboardEvent(KeyboardEvent.KEY_DOWN)
evttmp = e.clone() as KeyboardEvent
eventArray.push(evttmp);
t.addEventListener(TimerEvent.TIMER, timerout)
t.start()
e.stopPropagation()
e.preventDefault()
private function timerout(e:TimerEvent):void
trace("timerout")
t.stop()
NativeApplication.nativeApplication.removeEventListener(KeyboardEvent.KEY_DOWN, appKeyDown, true);
NativeApplication.nativeApplication.removeEventListener(KeyboardEvent.KEY_UP, appKeyUp, true);
NativeApplication.nativeApplication.removeEventListener(TextEvent.TEXT_INPUT, textinput, true);
for(var i:int=0; i<eventArray.length; i++)
barcodeField.dispatchEvent(eventArray[i])
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_DOWN, appKeyDown, true);
NativeApplication.nativeApplication.addEventListener(KeyboardEvent.KEY_UP, appKeyUp, true);
NativeApplication.nativeApplication.addEventListener(TextEvent.TEXT_INPUT, textinput, true);
]]>
</fx:Script>
the textinput event is never catch.
then I tried writing textinput event myself (in order to try if something appens) but I wasn't lucky
second test ---------
private function timerout(e:TimerEvent):void
trace("timerout")
t.stop()
NativeApplication.nativeApplication.removeEventListener(KeyboardEvent.KEY_DOWN, appKeyDown, true);
NativeApplication.nativeApplication.removeEventListener(KeyboardEvent.KEY_UP, appKeyUp, true);
barcodeField.dispatchEvent(eventArray[0])
var text:TextEvent = new TextEvent(TextEvent.TEXT_INPUT, true, false, bcd);
barcodeField.dispatchEvent(text);
barcodeField.dispatchEvent(eventArray[1]) -
Error #1009 in my Platform Game! Please Help!!!
In my basic platform game I have a "hero" that can walk and jump on the "ground." There is also a door to the next scene, which is the next level.The first scene works fine, but "TypeError: Error #1006: value is not a function. at Charles3_fla::MainTimeline/frame1()" pops up once in the output. It works however, and I'm not worried about it. The second I go throught the door though, Scene 2 opens, but then starts flashing as "TypeError: Error #1009: Cannot access a property or method of a null object reference. at Charles3_fla::MainTimeline/onenter()" pops up A LOT in the output. I don't know how to fix it, and would like help. P.S. I am using Adobe CS5 with actionscript 3
Here is the code for Scene 1:
hero.gotoAndStop('still');
var Key:KeyObject = new KeyObject(stage);
var vy:Number=0;
var gravity:Number=2;
var jumped:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME,onenter)(true);
function onenter(e:Event):void{
vy+=gravity;
if(! ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y+vy;
if(ground.hitTestPoint(hero.x+(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x-=13;
if(ground.hitTestPoint(hero.x-(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x+=13;
if (vy>10) {
vy=10;
for (var i:int = 0; i<10; i++) {
if (ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y--;
vy=6;
jumped=true;
if(door.hitTestObject(hero)){
gotoAndPlay(1,"Scene 2");
if(hero.y>300){
vy=6;
jumped=true;
if(Key.isDown(Key.UP) && jumped){
vy=-13;
jumped=false;
hero.y+=vy;
if(Key.isDown(Key.RIGHT)){
hero.x+=10;
hero.scaleX=1;
hero.gotoAndStop('walking');
}else if(Key.isDown(Key.LEFT)){
hero.x-=10;
hero.scaleX=-1;
hero.gotoAndStop('walking');
}else{
hero.gotoAndStop('still');
And for Scene 2...
hero.gotoAndStop('still');
var Key1:KeyObject =KeyObject(stage);
var vy1:Number=0;
var gravity1:Number=2;
var jumped1:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME,onenter1)(true);
function onenter1(e:Event):void{
vy1+=gravity;
if(! ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y+vy;
if(ground.hitTestPoint(hero.x+(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x-=13;
if(ground.hitTestPoint(hero.x-(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x+=13;
if (vy1>10) {
vy1=10;
for (var i:int = 0; i<10; i++) {
if (ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y--;
vy1=6;
jumped1=true;
if(door.hitTestObject(hero)){
gotoAndPlay(1,"Scene 2");
if(hero.y>300){
vy1=6;
jumped1=true;
if(Key.isDown(Key.UP) && jumped1){
vy1=-13;
jumped1=false;
hero.y+=vy;
if(Key.isDown(Key.RIGHT)){
hero.x+=10;
hero.scaleX=1;
hero.gotoAndStop('walking');
}else if(Key.isDown(Key.LEFT)){
hero.x-=10;
hero.scaleX=-1;
hero.gotoAndStop('walking');
}else{
hero.gotoAndStop('still');
Please reply as soon as possible, and thanks for your time
swiatekalex555Ok sorry about my misunderstanding. Here's the code with the errors Highlighted. I also downloaded a "KeyObject.as" package, and the contents of that are on the bottom.
hero.gotoAndStop('still');
var Key:KeyObject = new KeyObject(stage);
var vy:Number=0;
var gravity:Number=2;
var jumped:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME,onenter)(true);
function onenter(e:Event):void{
vy+=gravity;
if(! ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y+vy;
if(ground.hitTestPoint(hero.x+(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x-=13;
if(ground.hitTestPoint(hero.x-(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x+=13;
if (vy>10) {
vy=10;
for (var i:int = 0; i<10; i++) {
if (ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y--;
vy=6;
jumped=true;
if(door.hitTestObject(hero)){
gotoAndPlay(1,"Scene 2");
if(hero.y>300){
vy=6;
jumped=true;
if(Key.isDown(Key.UP) && jumped){
vy=-13;
jumped=false;
hero.y+=vy;
if(Key.isDown(Key.RIGHT)){
hero.x+=10;
hero.scaleX=1;
hero.gotoAndStop('walking');
}else if(Key.isDown(Key.LEFT)){
hero.x-=10;
hero.scaleX=-1;
hero.gotoAndStop('walking');
}else{
hero.gotoAndStop('still');
And for Scene 2...
hero.gotoAndStop('still');
var Key1:KeyObject =KeyObject(stage);
var vy1:Number=0;
var gravity1:Number=2;
var jumped1:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME,onenter1)(true);
function onenter1(e:Event):void{
vy1+=gravity;
if(! ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y+vy;
if(ground.hitTestPoint(hero.x+(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x-=13;
if(ground.hitTestPoint(hero.x-(hero.width/2), hero.y-(hero.height/2), true)) {
hero.x+=13;
if (vy1>10) {
vy1=10;
for (var i:int = 0; i<10; i++) {
if (ground.hitTestPoint(hero.x,hero.y,true)) {
hero.y--;
vy1=6;
jumped1=true;
if(door.hitTestObject(hero)){
gotoAndPlay(1,"Scene 2");
if(hero.y>300){
vy1=6;
jumped1=true;
if(Key.isDown(Key.UP) && jumped1){
vy1=-13;
jumped1=false;
hero.y+=vy;
if(Key.isDown(Key.RIGHT)){
hero.x+=10;
hero.scaleX=1;
hero.gotoAndStop('walking');
}else if(Key.isDown(Key.LEFT)){
hero.x-=10;
hero.scaleX=-1;
hero.gotoAndStop('walking');
}else{
hero.gotoAndStop('still');
the KeyObject.as
package {
import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
* The KeyObject class recreates functionality of
* Key.isDown of ActionScript 1 and 2
* Usage:
* var key:KeyObject = new KeyObject(stage);
* if (key.isDown(key.LEFT)) { ... }
dynamic public class KeyObject extends Proxy {
private static var stage:Stage;
private static var keysDown:Object;
public function KeyObject(stage:Stage) {
construct(stage);
public function construct(stage:Stage):void {
KeyObject.stage = stage;
keysDown = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
flash_proxy override function getProperty(name:*):* {
return (name in Keyboard) ? Keyboard[name] : -1;
public function isDown(keyCode:uint):Boolean {
return Boolean(keyCode in keysDown);
public function deconstruct():void {
stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, keyReleased);
keysDown = new Object();
KeyObject.stage = null;
private function keyPressed(evt:KeyboardEvent):void {
keysDown[evt.keyCode] = true;
private function keyReleased(evt:KeyboardEvent):void {
delete keysDown[evt.keyCode];
Help if you can,
swiatekalex555 -
I need help with shooting in my flash game for University
Hi there
Ive tried to make my tank in my game shoot, all the code that is there works but when i push space to shoot which is my shooting key it does not shoot I really need help with this and I would appriciate anyone that could help
listed below should be the correct code
//checking if the space bar is pressed and shooting is allowed
if(evt.keyCode == 32 && shootAllow){
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.y = tank_mc.y + tank_mc.width/2 - newBullet.width/2;
newBullet.x = tank_mc.x;
//then we add the bullet to stage
addChild(newBullet);
listed below is my entire code
import flash.display.MovieClip;
//declare varibles to create mines
//how much time before allowed to shoot again
var cTime:int = 0;
//the time it has to reach in order to be allowed to shoot (in frames)
var cLimit:int = 12;
//whether or not the user is allowed to shoot
var shootAllow:Boolean = true;
var minesInGame:uint;
var mineMaker:Timer;
var cursor:MovieClip;
var index:int=0;
var tankMine_mc:MovieClip;
var antiTankmine_mc:MovieClip;
var maxHP:int = 100;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;
function initialiseMine():void
minesInGame = 15;
//create a timer fires every second
mineMaker = new Timer(6000, minesInGame);
//tell timer to listen for Timer event
mineMaker.addEventListener(TimerEvent.TIMER, createMine);
//start the timer
mineMaker.start();
function createMine(event:TimerEvent):void
//var tankMine_mc:MovieClip;
//create a new instance of tankMine
tankMine_mc = new Mine();
//set the x and y axis
tankMine_mc.y = 513;
tankMine_mc.x = 1080;
// adds mines to stage
addChild(tankMine_mc);
tankMine_mc.addEventListener(Event.ENTER_FRAME, moveHorizontal);
function moveHorizontal(evt:Event):void{
evt.target.x -= Math.random()*5;
if (evt.target.x >= stage.stageWidth)
evt.target.removeEventListener(Event.ENTER_FRAME, moveHorizontal);
removeChild(DisplayObject(evt.target));
initialiseMine();
//declare varibles to create mines
var atmInGame:uint;
var atmMaker:Timer;
function initialiseAtm():void
atmInGame = 15;
//create a timer fires every second
atmMaker = new Timer(8000, minesInGame);
//tell timer to listen for Timer event
atmMaker.addEventListener(TimerEvent.TIMER, createAtm);
//start the timer
atmMaker.start();
function createAtm(event:TimerEvent):void
//var antiTankmine_mc
//create a new instance of tankMine
antiTankmine_mc = new Atm();
//set the x and y axis
antiTankmine_mc.y = 473;
antiTankmine_mc.x = 1080;
// adds mines to stage
addChild(antiTankmine_mc);
antiTankmine_mc.addEventListener(Event.ENTER_FRAME, moveHorizontal);
function moveHorizontal_2(evt:Event):void{
evt.target.x -= Math.random()*10;
if (evt.target.x >= stage.stageWidth)
evt.target.removeEventListener(Event.ENTER_FRAME, moveHorizontal);
removeChild(DisplayObject(evt.target));
initialiseAtm();
function moveForward():void{
bg_mc.x -=10;
function moveBackward():void{
bg_mc.x +=10;
var tank_mc:Tank;
// create a new Tank and put it into the variable
// tank_mc
tank_mc= new Tank;
// set the location ( x and y) of tank_mc
tank_mc.x=0;
tank_mc.y=375;
// show the tank_mc on the stage.
addChild(tank_mc);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onMovementKeys);
//creates the movement
function onMovementKeys(evt:KeyboardEvent):void
//makes the tank move by 10 pixels right
if (evt.keyCode==Keyboard.D)
tank_mc.x+=5;
//makes the tank move by 10 pixels left
if (evt.keyCode==Keyboard.A)
tank_mc.x-=5
//checking if the space bar is pressed and shooting is allowed
if(evt.keyCode == 32 && shootAllow){
//making it so the user can't shoot for a bit
shootAllow = false;
//declaring a variable to be a new Bullet
var newBullet:Bullet = new Bullet();
//changing the bullet's coordinates
newBullet.y = tank_mc.y + tank_mc.width/2 - newBullet.width/2;
newBullet.x = tank_mc.x;
//then we add the bullet to stage
addChild(newBullet);
if (tank_mc.hitTestObject(antiTankmine_mc))
//tank_mc.gotoAndPlay("hit");
currentHP -= 10;
// remove anti tank mine
removeChild(antiTankmine_mc);
if (tank_mc.hitTestObject(tankMine_mc))
//tank_mc.gotoAndPlay("hit");
currentHP -= 10;
// remove anti tank mine
removeChild(tankMine_mc);
//var maxHP:int = 100;
//var currentHP:int = maxHP;
//var percentHP:Number = currentHP / maxHP;
//Incrementing the cTime
//checking if cTime has reached the limit yet
if(cTime < cLimit){
cTime ++;
} else {
//if it has, then allow the user to shoot
shootAllow = true;
//and reset cTime
cTime = 0;
function updateHealthBar():void
percentHP = currentHP / maxHP;
healthBar.barColor.scaleX = percentHP;
if(currentHP <= 0)
currentHP = 0;
trace("Game Over");
updateHealthBar();USe the trace function to analyze what happens and what fails to happen in the code you showed. trace the conditional values to see if they are set up to allow a shot when you press the key
-
Hello, relatively new to AS3 and flash, this is the first time i am publishing anything. We are trying to upload our simple flashgame to our webserver, the game works perfectly fine locally save for one thing. We get an error regarding TLF which says it wont stream or something. So when it gets online, no sounds play and spacebar doesn't work, left and right arrow does work. We have three TLF text fields that are used to update score, lives and show you final score. If i turn these into classical text they stop working.
Things we have tried: Changing default linkage from RLS to Merged into code, changing the text boxes to classical text(they then stop working), made sure the paths are correct(all files are in the same directory including the .swz file)
This is the code from the soundclass:
package
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.events.*;
public class MySound
private var bgSound:Sound;
private var fireSound:Sound;
private var waterSound:Sound;
private var earthSound:Sound;
private var lightSound:Sound;
private var soundChannel:SoundChannel;
public function MySound()
soundChannel = new SoundChannel();
bgSound = new Sound();
var req:URLRequest = new URLRequest("BackgroundSound.mp3");
bgSound.load(req);
//fire
fireSound = new Sound();
var req2:URLRequest = new URLRequest("soundFire.mp3");
fireSound.load(req2);
// water
waterSound = new Sound();
var req3:URLRequest = new URLRequest("soundWater.mp3");
waterSound.load(req3);
// earth
earthSound = new Sound();
var req4:URLRequest = new URLRequest("soundEarth.mp3");
earthSound.load(req4);
// light
lightSound = new Sound();
var req5:URLRequest = new URLRequest("soundLight.mp3");
lightSound.load(req5);
public function playBgSound()
soundChannel = bgSound.play(0, 999999);
public function stopBgSound()
soundChannel.stop();
public function playFireSound()
fireSound.play();
public function playWaterSound()
waterSound.play();
public function playEarthSound()
earthSound.play();
public function playLightSound()
lightSound.play();
I can somewhat get that sound can bugg out, but why does spacebar stop functioning? ANy help is greatly appreciated as this has to be delivered in twelve hours(published online) for a school assignment.Also might add publishing it locally in my own browser everything works, as does ofcourse playing it in flash itself. Changing from RLS to merged into code stops the error from coming, but doesn´t fix the problem on the server.
Code from main class related to sound and spacebar:
import flash.display.*;
import flash.events.*;
import flash.ui.Keyboard;
import flash.text.TextField;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
public class main extends MovieClip
private var fireTimer:Timer; //delay between shots
private var canFire:Boolean = true;
private var mySound:MySound;
private var bulletSpeed:Number = -450;
public function main()
//load sounds
mySound = new MySound();
private function playGame(event:MouseEvent)
gotoAndStop(2);
// initialize
myLives = 5;
myHitsNo = 0;
weaponType = 1;
mybullets = new Array();
enemys = new Array();
myScoreTxt.text = "Score: " + myHitsNo;
myLivesTxt.text = "Lives: " + myLives;
fireTimer = new Timer(400, 1);
fireTimer.addEventListener(TimerEvent.TIMER, shootTimerHandler, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_DOWN, listenKeyDown);
stage.addEventListener(Event.ENTER_FRAME, addEnemy);
stage.addEventListener(Event.ENTER_FRAME, checkCollision);
player = new thePlayer(stage.stageWidth-40, spawnPoint2);// stage.stageHeight/2);
stage.focus = player;
addChild(player);
mySound.playBgSound();
public function listenKeyDown(event:KeyboardEvent) // Controls and weapontype selector
if (event.keyCode == 37) //left
player.movethePlayerDown();
if (event.keyCode == 39) //right
player.movethePlayerUp();
if (event.keyCode == Keyboard.SPACE) //space
shootBullet();
//soundFX.attachSound("Pistol Fire.wav");
//soundFX.start(); -
Help a newbie with Keyboard events
Right so I'm just getting started with ActionScript (and Flash) and I'm getting a bit confused. I've got quite a bit of experience programming in other languages but I've never touched either actionscript or flash before.
I've got various books and have tried searching around the internet but I can't find anything to help me with this problem... it looks to me like it SHOULD work (but obviously I'm wrong because it doesn't!) I'm just trying to get the base for a game set up, and want to be able to take in user input via the keyboard (I will want mouse control as well, but let's focus on this problem first).
My code is:
package {
import flash.display.MovieClip;
import flash.events.*;
import flash.ui.Keyboard;
public class Main extends MovieClip
var isRunning:Boolean = true;
public function Main()
trace("Flash Project!");
Initialize();
//Game Loop
while(isRunning)
Update();
trace("Exiting...");
public function Initialize():void
trace("Initializing!");
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyPressed);
public function Update():void
trace("Updating...");
public function OnKeyPressed(evt:KeyboardEvent):void
switch (evt.keyCode)
case Keyboard.ENTER:
trace("Enter!");
break;
case Keyboard.ESCAPE:
isRunning = false;
break;
case default:
trace("keyCode: ", event.keyCode);
break;
The errors it is generating refer to the OnKeyPressed function, and say that I have tried to access the undefined properties Keyboard, escape and default. I thought I imported all the keyboard stuff at the top? Help would be much appreciated here, I'll be fine once I'm up and running but at the moment I'm feeling somewhat lost.Right, well at least part of my problem was that I had
trace("keyCode: " event.keyCode);
instead of
trace("keyCode: " evt.keyCode);
but it still doesn't like the word "default"? This is strange as it's coming up in blue so it's obviosly recognising it as a keyword...
If I comment out the 'default' section of te switch case statement it get's stuck in an infinite loop, even if I press escape... which should set 'isRunning' false therefore exiting the loop...
Help! -
Hello everyone,
Currently if been busy with AS3 for a schoolproject however I'm facing all kind of problems.. If tried to contact a number of people for help, but neither they can help me with this. If searched my schoolbooks and of course the internet but I cant find anything about my issue.. Therefor I'm desperate and hoping someone on this forum is able to help me.
The current problem with my code is everytime I press the play again button in frame 4 and I restart my game it goes twice as fast. So I asked my teacher and she told me it's something with the EventHandlers but I didn't used them in my code. She's of no help to me currently.. Yes, education over here is worthless in a certain amount.. Personally I think to error lies in this code:
I also get the error called: TypeError: Error #1009 about a null object. It's at the MainTimeline/ enter_frame()..
import flash.text.TextField;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var laser:Laser;
var lazer:Lazer;
lazer = new Lazer();
var spaceBar:Boolean;
var channel:SoundChannel;
channel = new SoundChannel();
var vijand:enemy;
var ship:Personage;
var numberOfKilledEnemies:int = 0;
var localhoogste:SharedObject = SharedObject.getLocal("score");
var showscore:TextField;
var outputnaam:TextField;
var Levens:int = 3;
var shipHalfWidth:uint = ship.width / 2;
var shipHalfHeight:uint = ship.height / 2;
localhoogste.data.score = 0;
ship.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed_2);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed_2);
function limitStageBorder(ship:MovieClip)
if (ship.x + shipHalfWidth > stage.stageWidth)
ship.x = stage.stageWidth - shipHalfWidth;
else if (ship.x - shipHalfWidth <0)
ship.x = 0 + shipHalfWidth;
if (ship.y - shipHalfHeight < 0)
ship.y = 0 + shipHalfHeight;
else if (ship.y + shipHalfHeight > stage.stageHeight)
ship.y = stage.stageHeight - shipHalfHeight;
function fl_MoveInDirectionOfKey_2(event:Event)
outputnaam.text = ingevoerdenaam;
if(ship != null)
limitStageBorder(ship);
if (ship != null && upPressed == true)
ship.y -= 5;
if (ship != null && downPressed == true)
ship.y += 5;
if (ship != null && leftPressed == true)
ship.x -= 5;
if (ship != null && rightPressed == true)
ship.x += 5;
if (ship != null && vijand == null)
vijand = new enemy();
vijand.x = Math.random() * stage.stageWidth;
vijand.y = -10;
stage.addChild(vijand);
if (vijand != null)
vijand.y = vijand.y + 5;
if (vijand && vijand.y > stage.stageHeight)
stage.removeChild(vijand);
vijand = null;
if (vijand != null && vijand.hitTestObject(ship))
ship.gotoAndPlay(6);
vijand.gotoAndPlay(4);
Levens = Levens - 1;
ship = new Personage();
ship.x = Math.random() * stage.stageWidth;
ship.y = stage.stageHeight + ship.height / 2;
stage.addChild(ship);
stage.addChild(vijand);
vijand = null;
if (vijand != null && laser != null && vijand.hitTestObject(laser))
vijand.gotoAndPlay(4);
stage.removeChild(laser);
vijand = null;
laser = null;
numberOfKilledEnemies = numberOfKilledEnemies + 1;
showscore.text = String(numberOfKilledEnemies);
localhoogste.data.score = numberOfKilledEnemies;
vijand = new enemy();
vijand.x = Math.random() * stage.stageWidth;
vijand.y = -10;
stage.addChild(vijand);
function fl_SetKeyPressed_2(event:KeyboardEvent):void
switch (event.keyCode)
case Keyboard.UP :
upPressed = true;
break;
case Keyboard.DOWN :
downPressed = true;
break;
case Keyboard.LEFT :
leftPressed = true;
break;
case Keyboard.RIGHT :
rightPressed = true;
break;
function fl_UnsetKeyPressed_2(event:KeyboardEvent):void
switch (event.keyCode)
case Keyboard.UP :
upPressed = false;
break;
case Keyboard.DOWN :
downPressed = false;
break;
case Keyboard.LEFT :
leftPressed = false;
break;
case Keyboard.RIGHT :
rightPressed = false;
break;
ship.addEventListener(Event.ENTER_FRAME, enter_frame);
function enter_frame(event:Event):void
if (ship.hitTestObject(Blockade))
ship.y -= 10;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed, false, 0, true);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUP, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, updateGame, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, gameOver, false, 0, true);
function onKeyPressed(evt:KeyboardEvent):void
switch (evt.keyCode)
case Keyboard.SPACE :
spaceBar = true;
break;
function onKeyUP(evt:KeyboardEvent):void
switch (evt.keyCode)
case Keyboard.SPACE :
spaceBar = false;
break;
function updateGame(evt:Event):void
if (spaceBar)
if (laser == null)
laser = new Laser();
laser.x = ship.x;
laser.y = ship.y - 40;
stage.addChild(laser);
channel = lazer.play();
if (laser != null)
laser.y = laser.y - 10;
if (laser && laser.y <= 0)
stage.removeChild(laser);
laser = null;
showlife.text = String(Levens);
function gameOver(evt:Event):void
if (Levens < 1)
stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUP);
stage.removeEventListener(Event.ENTER_FRAME, updateGame);
ship.removeEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_2);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed_2);
stage.removeEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed_2);
stage.removeEventListener(Event.ENTER_FRAME, gameOver);
if (vijand != null)
stage.removeChild(vijand);
vijand = null;
if (ship != null)
stage.removeChild(ship);
ship = null;
if (laser != null)
stage.removeChild(laser);
laser = null;
gotoAndStop(4);Most of the errors are currently away.. The only problem now is that my game still goes twice as fast when I go from frame 4 ( button play again ) to frame 1, where you can enter your name again and go to frame 3 to play the game. The part wit /// was a tought of mine about how to get the ship to move slower again.. However it didn't work..
Here is my currently code:
import flash.text.TextField;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var laser:Laser;
var lazer:Lazer;
lazer = new Lazer();
var spaceBar:Boolean;
var channel:SoundChannel;
channel = new SoundChannel();
var vijand:enemy;
var ship:Personage;
var numberOfKilledEnemies:int = 0;
var localhoogste:SharedObject = SharedObject.getLocal("score");
var showscore:TextField;
var outputnaam:TextField;
var Levens:int = 3;
var shipHalfWidth:uint = ship.width / 2;
var shipHalfHeight:uint = ship.height / 2;
localhoogste.data.score = 0;
ship.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed_2);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed_2);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUP);
stage.addEventListener(Event.ENTER_FRAME, updateGame);
stage.addEventListener(Event.ENTER_FRAME, gameOver);
ship.addEventListener(Event.ENTER_FRAME, enter_frame);
function enter_frame(event:Event):void
if (ship != null && ship.hitTestObject(Blockade))
ship.y = ship.y -5;
function limitStageBorder(ship:MovieClip)
if (ship.x + shipHalfWidth > stage.stageWidth)
ship.x = stage.stageWidth - shipHalfWidth;
else if (ship.x - shipHalfWidth <0)
ship.x = 0 + shipHalfWidth;
if (ship.y - shipHalfHeight < 0)
ship.y = 0 + shipHalfHeight;
else if (ship.y + shipHalfHeight > stage.stageHeight)
ship.y = stage.stageHeight - shipHalfHeight;
function fl_MoveInDirectionOfKey_2(event:Event)
outputnaam.text = ingevoerdenaam;
if(ship != null)
limitStageBorder(ship);
// if (ship != null && upPressed == false)
// ship.y = ship.y -0;
// if (ship != null && downPressed == false)
// ship.y = ship.y +0;
// if (ship != null && leftPressed == false)
// ship.x = ship.x -0;
// if (ship!== null && rightPressed == false)
// ship.x = ship.x +0;
if (ship != null && upPressed == true)
ship.y = ship.y -5;
if (ship != null && downPressed == true)
ship.y = ship.y +5;
if (ship != null && leftPressed == true)
ship.x = ship.x -5;
if (ship != null && rightPressed == true)
ship.x = ship.x +5;
if (ship != null && vijand == null)
vijand = new enemy();
vijand.x = Math.random() * stage.stageWidth;
vijand.y = -10;
stage.addChild(vijand);
if (vijand != null)
vijand.y = vijand.y + 5;
if (vijand && vijand.y > stage.stageHeight)
stage.removeChild(vijand);
vijand = null;
if (vijand != null && vijand.hitTestObject(ship))
ship.gotoAndPlay(6);
vijand.gotoAndPlay(4);
Levens = Levens - 1;
ship = new Personage();
ship.x = Math.random() * stage.stageWidth;
ship.y = stage.stageHeight + ship.height / 2;
stage.addChild(ship);
stage.addChild(vijand);
vijand = null;
if (vijand != null && laser != null && vijand.hitTestObject(laser))
vijand.gotoAndPlay(4);
stage.removeChild(laser);
vijand = null;
laser = null;
numberOfKilledEnemies = numberOfKilledEnemies + 1;
showscore.text = String(numberOfKilledEnemies);
localhoogste.data.score = numberOfKilledEnemies;
vijand = new enemy();
vijand.x = Math.random() * stage.stageWidth;
vijand.y = vijand.y -5;
stage.addChild(vijand);
function fl_SetKeyPressed_2(event:KeyboardEvent):void
switch (event.keyCode)
case Keyboard.UP :
upPressed = true;
break;
case Keyboard.DOWN :
downPressed = true;
break;
case Keyboard.LEFT :
leftPressed = true;
break;
case Keyboard.RIGHT :
rightPressed = true;
break;
function fl_UnsetKeyPressed_2(event:KeyboardEvent):void
switch (event.keyCode)
case Keyboard.UP :
upPressed = false;
break;
case Keyboard.DOWN :
downPressed = false;
break;
case Keyboard.LEFT :
leftPressed = false;
break;
case Keyboard.RIGHT :
rightPressed = false;
break;
function onKeyPressed(evt:KeyboardEvent):void
switch (evt.keyCode)
case Keyboard.SPACE :
spaceBar = true;
break;
function onKeyUP(evt:KeyboardEvent):void
switch (evt.keyCode)
case Keyboard.SPACE :
spaceBar = false;
break;
function updateGame(evt:Event):void
if (spaceBar)
if (laser == null)
laser = new Laser();
laser.x = ship.x;
laser.y = ship.y - 40;
stage.addChild(laser);
channel = lazer.play();
if (laser != null)
laser.y = laser.y - 10;
if (laser && laser.y <= 0)
stage.removeChild(laser);
laser = null;
showlife.text = String(Levens);
function gameOver(evt:Event):void
if (Levens < 1)
stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUP);
stage.removeEventListener(Event.ENTER_FRAME, updateGame);
ship.removeEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_2);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed_2);
stage.removeEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed_2);
stage.removeEventListener(Event.ENTER_FRAME, gameOver);
ship.removeEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_2);
ship.removeEventListener(Event.ENTER_FRAME, enter_frame);
if (vijand != null)
stage.removeChild(vijand);
vijand = null;
if (ship != null)
stage.removeChild(ship);
ship = null;
if (laser != null)
stage.removeChild(laser);
laser = null;
gotoAndStop(4); -
Please! I need someone help with a game
I got this Error everytime the scene is reseted. I have no clue where mistake is made. Please help!
TypeError: Error #1010: A term is undefined and has no properties.
at golfer_fla::MainTimeline/resetScene()
at golfer_fla::MainTimeline/golfer_fla::frame1()
TypeError: Error #1010: A term is undefined and has no properties.
at golfer_fla::MainTimeline/resetScene()
at golfer_fla::MainTimeline/countDown()
at flash.utils::Timer/flash.utils:Timer::_timerDispatch()
at flash.utils::Timer/flash.utils:Timer::tick()
If that helps I could send my game by mail so someone could check the error which constantly pop out when the golfer hit the ball, ball stops and the scene resets.
Here is the code:
//Variables
var myHead = new head();
var myArms = new arms();
var myBody = new body();
var myStick = new stick();
var myGround = new ground();
var myFlag = new flag();
var myCapsel = new capsel();
var grassMask:Number;
var speedUp:int = 2;
var speedDown:int = speedUp * 8;
var checker:int;
var minPower:int;
var maxPower:int = 110;
var strength:Number;
var capselPower:Number;
var distance:Number;
var target:int;
var tryShot:int = 0;
var myTimer = new Timer(2000, 1);
//EventListeners
stage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onUp);
stage.addEventListener(Event.ENTER_FRAME, hit);
myTimer.addEventListener(TimerEvent.TIMER, countDown);
//Functions
function resetScene():void {
addChild(myBody);
addChild(myArms);
addChild(myHead);
addChild(myStick);
addChild(myGround);
addChild(myFlag);
addChild(myCapsel);
grassMask = (320 + Math.random()*260);
myBody.x = 70;
myBody.y = 296;
myArms.x = 68;
myArms.y = 276;
myArms.rotation = 0;
myHead.x = 70;
myHead.y = 215;
myStick.x = 68;
myStick.y = 276;
myStick.rotation = 0;
myCapsel.x = 90;
myCapsel.y = 331;
myGround.x = 0;
myGround.y = 375;
myGround.grassMask.x = grassMask - 610;
myFlag.x = grassMask;
myFlag.y = 375;
checker = 0;
minPower = 0;
target = 0;
tryShot ++;
myCapsel.capselFall.gotoAndStop(1);
myMessage.text = "Press any key!";
resetScene();
function invisibleCapsels():void {
a1.visible = false;
a2.visible = false;
a3.visible = false;
a4.visible = false;
a5.visible = false;
a6.visible = false;
a1.gotoAndStop(1);
a2.gotoAndStop(1);
a3.gotoAndStop(1);
a4.gotoAndStop(1);
a5.gotoAndStop(1);
a6.gotoAndStop(1);
invisibleCapsels();
function onDown(e:KeyboardEvent):void {
checker = 1;
minPower = -20;
function onUp(e:KeyboardEvent):void {
checker = 0;
capselPower = (myCapsel.x + myStick.rotation) * 3.2;
function hit(e:Event):void {
if(tryShot < 7) {
if((checker == 1) && (myStick.rotation < maxPower)) {
myStick.rotation += speedUp;
myArms.rotation += speedUp;
} else {
if(myStick.rotation > minPower) {
myStick.rotation -= speedDown;
myArms.rotation -= speedDown;
if(myStick.hitTestObject(myCapsel)) {
stage.addEventListener(Event.ENTER_FRAME, shot);
} else {
myMessage.text = "Game Over\nClick to play again";
stage.addEventListener(MouseEvent.MOUSE_DOWN, playAgain);
function playAgain(e:MouseEvent):void {
resetScene();
invisibleCapsels();
tryShot = 1;
stage.removeEventListener(MouseEvent.MOUSE_DOWN, playAgain);
function shot(e:Event):void {
strength = (capselPower - myCapsel.x);
distance = grassMask - myCapsel.x;
if((Math.round(distance) <= 10) && (Math.round(distance) >= 3) && (strength <= 65)) {
if(target == 0) {
myCapsel.capselFall.play();
myCapsel.rotation = 0;
target = 1;
this["a" + tryShot].visible = true;
myMessage.text = "Cooool!";
myTimer.start();
} else {
if(strength > 5) {
myCapsel.x += strength / 30;
myCapsel.rotation += strength / 4;
} else {
this["a" + tryShot].visible = true;
this["a" + tryShot].gotoAndStop(2);
myMessage.text = "Bad Luck!";
myTimer.start();
function countDown(e:TimerEvent):void {
resetScene();
stage.removeEventListener(Event.ENTER_FRAME, shot);Try adding the following two lines before line 59:
trace(myCapsel);
trace(myCapsel.capselFall);
If one of them traces undefined, it should isolate which object is the problem. If you describe what is involved with that object.child, then it may help generate an idea of what might be wrong. -
Is the help file wrong, or is it me?
Ok, so I am working through the help files, and am working on
"Enhancing the Hello World application", and I keep getting an
error message:
"1119: Access of possibly undefined property keyCode through
a reference with static type flash.events:Event."
Which is apparently having trouble with the following line of
code:
if (event.keyCode == Keyboard.ENTER)
The code is verbatim from the help file. I have checked
through and seen that keyCode does exist. Any thoughts?Reify32207,
> I keep getting an error message:
>
> "1119: Access of possibly undefined property keyCode
through
> a reference with static type flash.events:Event."
What you need, in this case, is an instance of the
KeyboardEvent class.
The Event class, alone, doesn't have a keyCode property, but
KeyboardEvent
(which extends Event) does.
> textIn.addEventListener(KeyboardEvent.KEY_UP,
keyPressed);
> function keyPressed(event:Event):void
That second line is the culprit. Should be this:
function keyPressed(event:KeyboardEvent):void
David Stiller
Co-author, Foundation Flash CS3 for Designers
http://tinyurl.com/2k29mj
"Luck is the residue of good design." -
Help Needed With Scrollbar and Content
I'm having a difficult time with the Scrollbar component. I'm trying to have a scrollbar set up to navigate a text field or a MC of a text field. I managed to get it functioning within the desired frame, however when I jump to another frame, that very same content appears on the other frame, despite the fact that said frame did not have the scrollbar nor the content pasted within.
The bar seems to do what I want it to do save for the unwelcomed presence outside of the frame of choice. Here's the code I'm using. This is the keyframe code:
import boppreh.ui.Scrollbar
var scrollbar1:Scrollbar = new Scrollbar(boomboom, 500, true, false, 293, bar, slider, arrowUp, arrowDown)
addChild(scrollbar1)
scrollbar1.x = 50
scrollbar1.y = 50
And this is the code found in the AS file:
package boppreh.ui
import flash.display.*
import flash.events.*
import flash.geom.Rectangle;
import flash.utils.Timer
import flash.ui.Keyboard
* Scrollbar to handle single display objects.
* Author: Lucas Boppre Niehues ([email protected])
* Date: 09/02/2010
public class Scrollbar extends Sprite {
/// The default width for the default slider, bar and arrows, as well as the default arrows' height
public static const DEFAULT_SIDE:Number = 20
/// The delay (in milliseconds) between clicking and holding an arrow and the slider moving continously
public static var SCROLL_DELAY:Number = 300
/// The number of lines to be scrolled every second during continous scrolling
public static var LINES_PER_SECOND:Number = 1.5
/// Number of pixels to be scrolled for each mouse wheel line (default lines per wheel tick is 3)
public static var PIXELS_PER_LINE:Number = 16
protected var windowSize:Number
protected var contentPadding:Number
protected var isVertical:Boolean
/// Stored movement to be applied on the next "scroll()" call
protected var movement:Number
/// Timer used to control the delay before continous scrolling
protected var timer:Timer
protected var content:DisplayObject
protected var contentBounds:Rectangle
protected var bar:InteractiveObject
protected var arrowUp:InteractiveObject
protected var arrowDown:InteractiveObject
protected var slider:InteractiveObject
protected var partHold:InteractiveObject
protected function get eventOrigin():String {
if (partHold == arrowUp)
return ScrollEvent.ARROW_UP
else if (partHold == arrowDown)
return ScrollEvent.ARROW_DOWN
else if (partHold == bar)
return ScrollEvent.BAR
throw new Error("Unkown event origin.")
private var mouseOffset:Number
protected function get maxContentPos():Number {
if (isVertical)
return -(contentBounds.height - windowSize) - 1
else
return -(contentBounds.width - windowSize) - 1
/// The content's current position, in a scale from 0 to 1
public function get position():Number {
if (isVertical)
return contentBounds.y / maxContentPos
else
return contentBounds.x / maxContentPos
public function set position(value:Number) {
value = Math.min(1, Math.max(value, 0))
var newContentPos:Number = value * maxContentPos
setPosition(content, isVertical ? null : newContentPos, isVertical ? newContentPos : null, false, false)
contentBounds = content.getBounds(this)
if (isVertical) {
bar.height = windowSize - (arrowUp.height + arrowDown.height)
slider.height = (windowSize / Math.max(contentBounds.height, windowSize)) * bar.height
var newSliderY:Number = arrowUp.height + (-newContentPos / contentBounds.height) * bar.height
setPosition(slider, null, newSliderY, false, false)
} else {
bar.width = windowSize - (arrowUp.width + arrowDown.width)
slider.width = (windowSize / Math.max(contentBounds.width, windowSize)) * bar.width
var newSliderX:Number = arrowUp.width + (-newContentPos / contentBounds.width) * bar.width
setPosition(slider, newSliderX, null, false, false)
updatePartsPositions()
* Creates a new Scrollbar object to scroll a single Display Object.
* @param content the object to be scrolled
* @param windowSize the height or width of the scrollbar, depending if it's vertical or not; i.e.: the dimension of the content's visible part
* @param isVertical defines if the scrollbar's parts should be placed on the right or bottom of the content, and if the content should be scrolled upways or to the right
* @param autoUpdate automatically checks for dimensions changes in any part and updates accordingly. Use only if the content will be resized
* @param contentPadding the distance between the content and all the other parts
* @param bar the bar object to be used; if null, a default one will be used
* @param slider the slider object to be used; if null, a default one will be used
* @param arrowUp the arrow up/left object to be used; if null, a default one will be used
* @param arrowDown the arrow down/right object to be used; if null, a default one will be used
public function Scrollbar(content:DisplayObject, windowSize:Number, isVertical:Boolean=true, autoUpdate:Boolean=false, contentPadding:Number=5, bar:InteractiveObject=null, slider:InteractiveObject=null, arrowUp:InteractiveObject=null, arrowDown:InteractiveObject=null) {
this.content = content
this.windowSize = windowSize
this.contentPadding = contentPadding
this.isVertical = isVertical
this.bar = bar || createDefaultBar()
this.arrowUp = arrowUp || createDefaultArrow(false)
this.arrowDown = arrowDown || createDefaultArrow(true)
this.slider = slider || createDefaultSlider()
timer = new Timer(SCROLL_DELAY)
timer.addEventListener(TimerEvent.TIMER, startScrolling)
addParts()
if (autoUpdate)
this.addEventListener(Event.ENTER_FRAME, update)
configureListeners()
update()
position = 0
protected function scroll(e:*= null):void {
// This nested if forbids the slider to continue moving if the user is
// "holding" the bar and the slider already reached the mouse position
if (e && (e is Event) && (Event(e).type == Event.ENTER_FRAME)) {
if (partHold == bar) {
var sliderBounds:Rectangle = slider.getBounds(this)
if (isVertical) {
if (mouseY > sliderBounds.top && mouseY < sliderBounds.bottom) {
stopScrolling()
return
} else {
if (mouseX > sliderBounds.left && mouseX < sliderBounds.right) {
stopScrolling()
return
scrollPixels(movement)
* Scrolls the content by the specified ammount.
* @param number number of pixels to be scrolled
protected function scrollPixels(number:Number):void {
position += number / -maxContentPos
protected function configureListeners():void {
slider.addEventListener(MouseEvent.MOUSE_DOWN, startSliderDrag)
for each (var part:InteractiveObject in [arrowUp, arrowDown, bar]) {
part.addEventListener(MouseEvent.MOUSE_DOWN, fixedPart_onMouseDownHandler)
addEventListener(MouseEvent.MOUSE_WHEEL, mouse_onWheelScrollHandler)
addEventListener(KeyboardEvent.KEY_DOWN, keyboard_onKeyDownHandler)
protected function fixedPart_onMouseDownHandler(event:MouseEvent):void
partHold = InteractiveObject(event.currentTarget)
if (partHold == arrowUp) {
movement = -PIXELS_PER_LINE
} else if (partHold == arrowDown) {
movement = PIXELS_PER_LINE
} else if (partHold == bar) {
var sliderBounds:Rectangle = slider.getBounds(this)
if (isVertical) {
if (mouseY > (sliderBounds.top + sliderBounds.height / 2))
movement = windowSize
else
movement = -windowSize
} else {
if (mouseX > (sliderBounds.left + sliderBounds.width / 2))
movement = windowSize
else
movement = -windowSize
scroll()
dispatchEvent(new ScrollEvent(ScrollEvent.SCROLL, eventOrigin))
stage.addEventListener(MouseEvent.MOUSE_UP, stopScrolling)
partHold.addEventListener(MouseEvent.MOUSE_OUT, stopScrolling)
timer.start()
protected function keyboard_onKeyDownHandler(event:KeyboardEvent):void {
switch (event.keyCode) {
case Keyboard.UP:
case Keyboard.LEFT:
movement = -PIXELS_PER_LINE
break
case Keyboard.DOWN:
case Keyboard.RIGHT:
movement = PIXELS_PER_LINE
break
case Keyboard.SPACE:
case Keyboard.PAGE_DOWN:
movement = windowSize
break
case Keyboard.PAGE_UP:
movement = -windowSize
break
case Keyboard.HOME:
movement = 0
position = 0
break
case Keyboard.END:
movement = 0
position = 100
break
default:
return
scroll()
dispatchEvent(new ScrollEvent(ScrollEvent.SCROLL, ScrollEvent.KEYBOARD))
protected function startScrolling(e:*=null):void {
timer.reset()
this.addEventListener(Event.ENTER_FRAME, scroll)
movement = (movement * (LINES_PER_SECOND * PIXELS_PER_LINE)) / stage.frameRate
dispatchEvent(new ScrollEvent(ScrollEvent.CONTINOUS_SCROLL_START, eventOrigin))
protected function stopScrolling(e:*=null) {
timer.stop()
this.removeEventListener(Event.ENTER_FRAME, scroll)
stage.removeEventListener(KeyboardEvent.KEY_UP, stopScrolling)
stage.removeEventListener(MouseEvent.MOUSE_UP, stopScrolling)
dispatchEvent(new ScrollEvent(ScrollEvent.CONTINOUS_SCROLL_STOP, eventOrigin))
if (partHold) {
partHold.removeEventListener(MouseEvent.MOUSE_OUT, stopScrolling)
partHold = null
protected function mouse_onWheelScrollHandler(event:MouseEvent) {
// The mouse wheel delta arrives inverted
var delta:int = -event.delta
movement = delta * PIXELS_PER_LINE
scroll()
dispatchEvent(new ScrollEvent(ScrollEvent.SCROLL, ScrollEvent.MOUSE_WHEEL))
//{ region Slider Drag functions
protected function startSliderDrag(event:MouseEvent) {
if (isVertical)
mouseOffset = slider.getBounds(this).y - this.mouseY
else
mouseOffset = slider.getBounds(this).x - this.mouseX
stage.addEventListener(MouseEvent.MOUSE_MOVE, onSliderDrag)
stage.addEventListener(MouseEvent.MOUSE_UP, stopSliderDrag)
dispatchEvent(new ScrollEvent(ScrollEvent.SLIDER_DRAG_START, ScrollEvent.SLIDER))
protected function stopSliderDrag(event:MouseEvent) {
stage.removeEventListener(MouseEvent.MOUSE_UP, stopSliderDrag)
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onSliderDrag)
dispatchEvent(new ScrollEvent(ScrollEvent.SLIDER_DRAG_STOP, ScrollEvent.SLIDER))
protected function onSliderDrag(event:MouseEvent) {
if (isVertical) {
if (bar.height == slider.height)
return
} else {
if (bar.width == slider.width)
return
if (isVertical)
position = (this.mouseY + mouseOffset - arrowUp.height) / (bar.height - slider.height)
else
position = (this.mouseX + mouseOffset - arrowUp.width) / (bar.width - slider.width)
//} endregion
//{ region Visual functions
/// Adds all required parts to the scrollbar's display list
protected function addParts():void {
setPosition(content, 0, 0, false, false)
addChild(this.bar)
addChild(this.arrowUp)
addChild(this.arrowDown)
addChild(this.slider)
addChild(this.content)
* Updates all parts to fit the new dimensions and positions.
public function update(e:*= null):void {
contentBounds = content.getBounds(this)
updatePartsPositions()
// Ugly, but updates everything that was not update in the above call based on the content's position and size
position = position
protected function updatePartsPositions(event:Event = null):void {
if (isVertical) {
// The parts width is divided by 2 because they will be center aligned
var newX:Number = contentBounds.width +
contentPadding +
Math.max(slider.width, arrowUp.width, arrowDown.width, bar.width) / 2
setPosition(arrowUp, newX, 0, true, false)
setPosition(bar, newX, arrowUp.height, true, false)
setPosition(arrowDown, newX, arrowUp.height + bar.height, true, false)
setPosition(slider, newX, null, true, false)
} else {
var newY:Number = contentBounds.height +
contentPadding +
Math.max(slider.height, arrowUp.height, arrowDown.height, bar.height) / 2
setPosition(arrowUp, 0, newY, false, true)
setPosition(bar, arrowUp.width, newY, false, true)
setPosition(arrowDown, arrowUp.width + bar.width, newY, false, true)
setPosition(slider, null, newY, false, true)
updateMask()
private function updateMask():void {
if (content.mask && this.contains(content.mask))
removeChild(content.mask)
var contentMask:Sprite = createWindowMask()
addChild(contentMask)
content.mask = contentMask
protected function setPosition(part:DisplayObject, newX:Object=null, newY:Object=null, alignHorizontal:Boolean=false, alignVertical:Boolean=false):void {
var bounds:Rectangle = part.getBounds(this)
if (newX is Number)
part.x = int(newX) + (part.x - bounds.x) - ((alignHorizontal) ? bounds.width / 2 : 0)
if (newY is Number)
part.y = int(newY) + (part.y - bounds.y) - ((alignVertical) ? bounds.height / 2 : 0)
//} endregion
//{ region Functions to draw parts
private function createDefaultBar():Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(1)
image.graphics.beginFill(0xFFFFFF)
if (isVertical)
image.graphics.drawRect(0, 0, DEFAULT_SIDE, windowSize - DEFAULT_SIDE * 2)
else
image.graphics.drawRect(0, 0, windowSize - DEFAULT_SIDE * 2, DEFAULT_SIDE)
image.graphics.endFill()
//image.buttonMode = true
return image
private function createDefaultArrow(inverted:Boolean):Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(1)
image.graphics.beginFill(0xBFBFBF)
image.graphics.drawRect(0, 0, DEFAULT_SIDE, DEFAULT_SIDE)
image.graphics.endFill()
image.graphics.lineStyle(3)
if (isVertical) {
if (inverted) {
image.graphics.moveTo(4, 4)
image.graphics.lineTo(10, 16)
image.graphics.lineTo(16, 4)
} else {
image.graphics.moveTo(4, 16)
image.graphics.lineTo(10, 4)
image.graphics.lineTo(16, 16)
} else {
if (inverted) {
image.graphics.moveTo(4, 4)
image.graphics.lineTo(16, 10)
image.graphics.lineTo(4, 16)
} else {
image.graphics.moveTo(16, 4)
image.graphics.lineTo(4, 10)
image.graphics.lineTo(16, 16)
image.buttonMode = true
return image
private function createDefaultSlider():Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(1)
image.graphics.beginFill(0xBFBFBF)
if (isVertical)
image.graphics.drawRect(0, 0, DEFAULT_SIDE, windowSize - DEFAULT_SIDE * 2)
else
image.graphics.drawRect(0, 0, windowSize - DEFAULT_SIDE * 2, DEFAULT_SIDE)
image.graphics.endFill()
image.buttonMode = true
return image
private function createWindowMask():Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(0)
image.graphics.beginFill(0x000000, 1)
if (isVertical)
image.graphics.drawRect(0, 0, content.width + 1, windowSize)
else
image.graphics.drawRect(0, 0, windowSize, content.width + 1)
image.graphics.endFill()
image.alpha = 0
return image
//} endregion
And this is the ScrollEvent AS file:
package boppreh.ui
import flash.events.Event;
* Events related to the Scrollbar class.
* Author: Lucas Boppre Niehues ([email protected])
* Date: 09/02/2010
public class ScrollEvent extends Event
/// Dispatched when a scroll movement occurs
public static const SCROLL:String = "scroll"
/// Dispatched when the user has clicked and is holding an arrow or the bar
public static const CONTINOUS_SCROLL_START:String = "continous scroll start"
/// Dispatched when the user has clicked and dropped an arrow or the bar
public static const CONTINOUS_SCROLL_STOP:String = "continous scroll stop"
/// Dispatched when the user starts dragging the slider part
public static const SLIDER_DRAG_START:String = "slider drag start"
/// Dispatched when the user stops dragging the slider part
public static const SLIDER_DRAG_STOP:String = "slider drag stop"
/// Origin type representing the arrow up part
public static const ARROW_UP:String = "arrow up"
/// Origin type representing the arrow down part
public static const ARROW_DOWN:String = "arrow down"
/// Origin type representing the bar part
public static const BAR:String = "part"
/// Origin type representing the slider part
public static const SLIDER:String = "slider"
/// Origin type representing the keyboard
public static const KEYBOARD:String = "keyboard"
/// Origin type representing the mouse wheel
public static const MOUSE_WHEEL:String = "mouse wheel"
public var origin:String
* Creates a new ScrollEvent object.
* @param type the object type (first group of declared constants)
* @param origin the object that originated the event (second group of declared constants)
public function ScrollEvent (type:String, origin:String, bubbles:Boolean = false, cancelable:Boolean = false) {
this.origin = origin
super(type, bubbles, cancelable)
Any help would be appreciated. I've been stuck here all day.I'm having a difficult time with the Scrollbar component. I'm trying to have a scrollbar set up to navigate a text field or a MC of a text field. I managed to get it functioning within the desired frame, however when I jump to another frame, that very same content appears on the other frame, despite the fact that said frame did not have the scrollbar nor the content pasted within.
The bar seems to do what I want it to do save for the unwelcomed presence outside of the frame of choice. Here's the code I'm using. This is the keyframe code:
import boppreh.ui.Scrollbar
var scrollbar1:Scrollbar = new Scrollbar(boomboom, 500, true, false, 293, bar, slider, arrowUp, arrowDown)
addChild(scrollbar1)
scrollbar1.x = 50
scrollbar1.y = 50
And this is the code found in the AS file:
package boppreh.ui
import flash.display.*
import flash.events.*
import flash.geom.Rectangle;
import flash.utils.Timer
import flash.ui.Keyboard
* Scrollbar to handle single display objects.
* Author: Lucas Boppre Niehues ([email protected])
* Date: 09/02/2010
public class Scrollbar extends Sprite {
/// The default width for the default slider, bar and arrows, as well as the default arrows' height
public static const DEFAULT_SIDE:Number = 20
/// The delay (in milliseconds) between clicking and holding an arrow and the slider moving continously
public static var SCROLL_DELAY:Number = 300
/// The number of lines to be scrolled every second during continous scrolling
public static var LINES_PER_SECOND:Number = 1.5
/// Number of pixels to be scrolled for each mouse wheel line (default lines per wheel tick is 3)
public static var PIXELS_PER_LINE:Number = 16
protected var windowSize:Number
protected var contentPadding:Number
protected var isVertical:Boolean
/// Stored movement to be applied on the next "scroll()" call
protected var movement:Number
/// Timer used to control the delay before continous scrolling
protected var timer:Timer
protected var content:DisplayObject
protected var contentBounds:Rectangle
protected var bar:InteractiveObject
protected var arrowUp:InteractiveObject
protected var arrowDown:InteractiveObject
protected var slider:InteractiveObject
protected var partHold:InteractiveObject
protected function get eventOrigin():String {
if (partHold == arrowUp)
return ScrollEvent.ARROW_UP
else if (partHold == arrowDown)
return ScrollEvent.ARROW_DOWN
else if (partHold == bar)
return ScrollEvent.BAR
throw new Error("Unkown event origin.")
private var mouseOffset:Number
protected function get maxContentPos():Number {
if (isVertical)
return -(contentBounds.height - windowSize) - 1
else
return -(contentBounds.width - windowSize) - 1
/// The content's current position, in a scale from 0 to 1
public function get position():Number {
if (isVertical)
return contentBounds.y / maxContentPos
else
return contentBounds.x / maxContentPos
public function set position(value:Number) {
value = Math.min(1, Math.max(value, 0))
var newContentPos:Number = value * maxContentPos
setPosition(content, isVertical ? null : newContentPos, isVertical ? newContentPos : null, false, false)
contentBounds = content.getBounds(this)
if (isVertical) {
bar.height = windowSize - (arrowUp.height + arrowDown.height)
slider.height = (windowSize / Math.max(contentBounds.height, windowSize)) * bar.height
var newSliderY:Number = arrowUp.height + (-newContentPos / contentBounds.height) * bar.height
setPosition(slider, null, newSliderY, false, false)
} else {
bar.width = windowSize - (arrowUp.width + arrowDown.width)
slider.width = (windowSize / Math.max(contentBounds.width, windowSize)) * bar.width
var newSliderX:Number = arrowUp.width + (-newContentPos / contentBounds.width) * bar.width
setPosition(slider, newSliderX, null, false, false)
updatePartsPositions()
* Creates a new Scrollbar object to scroll a single Display Object.
* @param content the object to be scrolled
* @param windowSize the height or width of the scrollbar, depending if it's vertical or not; i.e.: the dimension of the content's visible part
* @param isVertical defines if the scrollbar's parts should be placed on the right or bottom of the content, and if the content should be scrolled upways or to the right
* @param autoUpdate automatically checks for dimensions changes in any part and updates accordingly. Use only if the content will be resized
* @param contentPadding the distance between the content and all the other parts
* @param bar the bar object to be used; if null, a default one will be used
* @param slider the slider object to be used; if null, a default one will be used
* @param arrowUp the arrow up/left object to be used; if null, a default one will be used
* @param arrowDown the arrow down/right object to be used; if null, a default one will be used
public function Scrollbar(content:DisplayObject, windowSize:Number, isVertical:Boolean=true, autoUpdate:Boolean=false, contentPadding:Number=5, bar:InteractiveObject=null, slider:InteractiveObject=null, arrowUp:InteractiveObject=null, arrowDown:InteractiveObject=null) {
this.content = content
this.windowSize = windowSize
this.contentPadding = contentPadding
this.isVertical = isVertical
this.bar = bar || createDefaultBar()
this.arrowUp = arrowUp || createDefaultArrow(false)
this.arrowDown = arrowDown || createDefaultArrow(true)
this.slider = slider || createDefaultSlider()
timer = new Timer(SCROLL_DELAY)
timer.addEventListener(TimerEvent.TIMER, startScrolling)
addParts()
if (autoUpdate)
this.addEventListener(Event.ENTER_FRAME, update)
configureListeners()
update()
position = 0
protected function scroll(e:*= null):void {
// This nested if forbids the slider to continue moving if the user is
// "holding" the bar and the slider already reached the mouse position
if (e && (e is Event) && (Event(e).type == Event.ENTER_FRAME)) {
if (partHold == bar) {
var sliderBounds:Rectangle = slider.getBounds(this)
if (isVertical) {
if (mouseY > sliderBounds.top && mouseY < sliderBounds.bottom) {
stopScrolling()
return
} else {
if (mouseX > sliderBounds.left && mouseX < sliderBounds.right) {
stopScrolling()
return
scrollPixels(movement)
* Scrolls the content by the specified ammount.
* @param number number of pixels to be scrolled
protected function scrollPixels(number:Number):void {
position += number / -maxContentPos
protected function configureListeners():void {
slider.addEventListener(MouseEvent.MOUSE_DOWN, startSliderDrag)
for each (var part:InteractiveObject in [arrowUp, arrowDown, bar]) {
part.addEventListener(MouseEvent.MOUSE_DOWN, fixedPart_onMouseDownHandler)
addEventListener(MouseEvent.MOUSE_WHEEL, mouse_onWheelScrollHandler)
addEventListener(KeyboardEvent.KEY_DOWN, keyboard_onKeyDownHandler)
protected function fixedPart_onMouseDownHandler(event:MouseEvent):void
partHold = InteractiveObject(event.currentTarget)
if (partHold == arrowUp) {
movement = -PIXELS_PER_LINE
} else if (partHold == arrowDown) {
movement = PIXELS_PER_LINE
} else if (partHold == bar) {
var sliderBounds:Rectangle = slider.getBounds(this)
if (isVertical) {
if (mouseY > (sliderBounds.top + sliderBounds.height / 2))
movement = windowSize
else
movement = -windowSize
} else {
if (mouseX > (sliderBounds.left + sliderBounds.width / 2))
movement = windowSize
else
movement = -windowSize
scroll()
dispatchEvent(new ScrollEvent(ScrollEvent.SCROLL, eventOrigin))
stage.addEventListener(MouseEvent.MOUSE_UP, stopScrolling)
partHold.addEventListener(MouseEvent.MOUSE_OUT, stopScrolling)
timer.start()
protected function keyboard_onKeyDownHandler(event:KeyboardEvent):void {
switch (event.keyCode) {
case Keyboard.UP:
case Keyboard.LEFT:
movement = -PIXELS_PER_LINE
break
case Keyboard.DOWN:
case Keyboard.RIGHT:
movement = PIXELS_PER_LINE
break
case Keyboard.SPACE:
case Keyboard.PAGE_DOWN:
movement = windowSize
break
case Keyboard.PAGE_UP:
movement = -windowSize
break
case Keyboard.HOME:
movement = 0
position = 0
break
case Keyboard.END:
movement = 0
position = 100
break
default:
return
scroll()
dispatchEvent(new ScrollEvent(ScrollEvent.SCROLL, ScrollEvent.KEYBOARD))
protected function startScrolling(e:*=null):void {
timer.reset()
this.addEventListener(Event.ENTER_FRAME, scroll)
movement = (movement * (LINES_PER_SECOND * PIXELS_PER_LINE)) / stage.frameRate
dispatchEvent(new ScrollEvent(ScrollEvent.CONTINOUS_SCROLL_START, eventOrigin))
protected function stopScrolling(e:*=null) {
timer.stop()
this.removeEventListener(Event.ENTER_FRAME, scroll)
stage.removeEventListener(KeyboardEvent.KEY_UP, stopScrolling)
stage.removeEventListener(MouseEvent.MOUSE_UP, stopScrolling)
dispatchEvent(new ScrollEvent(ScrollEvent.CONTINOUS_SCROLL_STOP, eventOrigin))
if (partHold) {
partHold.removeEventListener(MouseEvent.MOUSE_OUT, stopScrolling)
partHold = null
protected function mouse_onWheelScrollHandler(event:MouseEvent) {
// The mouse wheel delta arrives inverted
var delta:int = -event.delta
movement = delta * PIXELS_PER_LINE
scroll()
dispatchEvent(new ScrollEvent(ScrollEvent.SCROLL, ScrollEvent.MOUSE_WHEEL))
//{ region Slider Drag functions
protected function startSliderDrag(event:MouseEvent) {
if (isVertical)
mouseOffset = slider.getBounds(this).y - this.mouseY
else
mouseOffset = slider.getBounds(this).x - this.mouseX
stage.addEventListener(MouseEvent.MOUSE_MOVE, onSliderDrag)
stage.addEventListener(MouseEvent.MOUSE_UP, stopSliderDrag)
dispatchEvent(new ScrollEvent(ScrollEvent.SLIDER_DRAG_START, ScrollEvent.SLIDER))
protected function stopSliderDrag(event:MouseEvent) {
stage.removeEventListener(MouseEvent.MOUSE_UP, stopSliderDrag)
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onSliderDrag)
dispatchEvent(new ScrollEvent(ScrollEvent.SLIDER_DRAG_STOP, ScrollEvent.SLIDER))
protected function onSliderDrag(event:MouseEvent) {
if (isVertical) {
if (bar.height == slider.height)
return
} else {
if (bar.width == slider.width)
return
if (isVertical)
position = (this.mouseY + mouseOffset - arrowUp.height) / (bar.height - slider.height)
else
position = (this.mouseX + mouseOffset - arrowUp.width) / (bar.width - slider.width)
//} endregion
//{ region Visual functions
/// Adds all required parts to the scrollbar's display list
protected function addParts():void {
setPosition(content, 0, 0, false, false)
addChild(this.bar)
addChild(this.arrowUp)
addChild(this.arrowDown)
addChild(this.slider)
addChild(this.content)
* Updates all parts to fit the new dimensions and positions.
public function update(e:*= null):void {
contentBounds = content.getBounds(this)
updatePartsPositions()
// Ugly, but updates everything that was not update in the above call based on the content's position and size
position = position
protected function updatePartsPositions(event:Event = null):void {
if (isVertical) {
// The parts width is divided by 2 because they will be center aligned
var newX:Number = contentBounds.width +
contentPadding +
Math.max(slider.width, arrowUp.width, arrowDown.width, bar.width) / 2
setPosition(arrowUp, newX, 0, true, false)
setPosition(bar, newX, arrowUp.height, true, false)
setPosition(arrowDown, newX, arrowUp.height + bar.height, true, false)
setPosition(slider, newX, null, true, false)
} else {
var newY:Number = contentBounds.height +
contentPadding +
Math.max(slider.height, arrowUp.height, arrowDown.height, bar.height) / 2
setPosition(arrowUp, 0, newY, false, true)
setPosition(bar, arrowUp.width, newY, false, true)
setPosition(arrowDown, arrowUp.width + bar.width, newY, false, true)
setPosition(slider, null, newY, false, true)
updateMask()
private function updateMask():void {
if (content.mask && this.contains(content.mask))
removeChild(content.mask)
var contentMask:Sprite = createWindowMask()
addChild(contentMask)
content.mask = contentMask
protected function setPosition(part:DisplayObject, newX:Object=null, newY:Object=null, alignHorizontal:Boolean=false, alignVertical:Boolean=false):void {
var bounds:Rectangle = part.getBounds(this)
if (newX is Number)
part.x = int(newX) + (part.x - bounds.x) - ((alignHorizontal) ? bounds.width / 2 : 0)
if (newY is Number)
part.y = int(newY) + (part.y - bounds.y) - ((alignVertical) ? bounds.height / 2 : 0)
//} endregion
//{ region Functions to draw parts
private function createDefaultBar():Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(1)
image.graphics.beginFill(0xFFFFFF)
if (isVertical)
image.graphics.drawRect(0, 0, DEFAULT_SIDE, windowSize - DEFAULT_SIDE * 2)
else
image.graphics.drawRect(0, 0, windowSize - DEFAULT_SIDE * 2, DEFAULT_SIDE)
image.graphics.endFill()
//image.buttonMode = true
return image
private function createDefaultArrow(inverted:Boolean):Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(1)
image.graphics.beginFill(0xBFBFBF)
image.graphics.drawRect(0, 0, DEFAULT_SIDE, DEFAULT_SIDE)
image.graphics.endFill()
image.graphics.lineStyle(3)
if (isVertical) {
if (inverted) {
image.graphics.moveTo(4, 4)
image.graphics.lineTo(10, 16)
image.graphics.lineTo(16, 4)
} else {
image.graphics.moveTo(4, 16)
image.graphics.lineTo(10, 4)
image.graphics.lineTo(16, 16)
} else {
if (inverted) {
image.graphics.moveTo(4, 4)
image.graphics.lineTo(16, 10)
image.graphics.lineTo(4, 16)
} else {
image.graphics.moveTo(16, 4)
image.graphics.lineTo(4, 10)
image.graphics.lineTo(16, 16)
image.buttonMode = true
return image
private function createDefaultSlider():Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(1)
image.graphics.beginFill(0xBFBFBF)
if (isVertical)
image.graphics.drawRect(0, 0, DEFAULT_SIDE, windowSize - DEFAULT_SIDE * 2)
else
image.graphics.drawRect(0, 0, windowSize - DEFAULT_SIDE * 2, DEFAULT_SIDE)
image.graphics.endFill()
image.buttonMode = true
return image
private function createWindowMask():Sprite {
var image:Sprite = new Sprite()
image.graphics.lineStyle(0)
image.graphics.beginFill(0x000000, 1)
if (isVertical)
image.graphics.drawRect(0, 0, content.width + 1, windowSize)
else
image.graphics.drawRect(0, 0, windowSize, content.width + 1)
image.graphics.endFill()
image.alpha = 0
return image
//} endregion
And this is the ScrollEvent AS file:
package boppreh.ui
import flash.events.Event;
* Events related to the Scrollbar class.
* Author: Lucas Boppre Niehues ([email protected])
* Date: 09/02/2010
public class ScrollEvent extends Event
/// Dispatched when a scroll movement occurs
public static const SCROLL:String = "scroll"
/// Dispatched when the user has clicked and is holding an arrow or the bar
public static const CONTINOUS_SCROLL_START:String = "continous scroll start"
/// Dispatched when the user has clicked and dropped an arrow or the bar
public static const CONTINOUS_SCROLL_STOP:String = "continous scroll stop"
/// Dispatched when the user starts dragging the slider part
public static const SLIDER_DRAG_START:String = "slider drag start"
/// Dispatched when the user stops dragging the slider part
public static const SLIDER_DRAG_STOP:String = "slider drag stop"
/// Origin type representing the arrow up part
public static const ARROW_UP:String = "arrow up"
/// Origin type representing the arrow down part
public static const ARROW_DOWN:String = "arrow down"
/// Origin type representing the bar part
public static const BAR:String = "part"
/// Origin type representing the slider part
public static const SLIDER:String = "slider"
/// Origin type representing the keyboard
public static const KEYBOARD:String = "keyboard"
/// Origin type representing the mouse wheel
public static const MOUSE_WHEEL:String = "mouse wheel"
public var origin:String
* Creates a new ScrollEvent object.
* @param type the object type (first group of declared constants)
* @param origin the object that originated the event (second group of declared constants)
public function ScrollEvent (type:String, origin:String, bubbles:Boolean = false, cancelable:Boolean = false) {
this.origin = origin
super(type, bubbles, cancelable)
Any help would be appreciated. I've been stuck here all day. -
Help Please!!! AS3 Platform game
I am creating a a platform game for one of my classes. I am not fimilar with Flash and I am having trouble with the coding. I keep getting this error message
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at TheBallMan2_fla::MainTimeline/frame4()
at flash.display::MovieClip/gotoAndStop()
at TheBallMan2_fla::MainTimeline/fl_ClickToGoToAndStopAtFrame_12()
TheBallMan2 is the name I have my project saved as.
My partner did all the coding but he doesn't really know what he is doing either. The character is supposed to move with the arrow keys which it did until we added the collision code. Here is our coding...which we got from following a tutorial online.
/* Click to Go to Frame and Stop
Clicking on the specified symbol instance moves the playhead to the specified frame in the timeline and stops the movie.
Can be used on the main timeline or on movie clip timelines.
Instructions:
1. Replace the number 5 in the code below with the frame number you would like the playhead to move to when the symbol instance is clicked.
About.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_3);
function fl_ClickToGoToAndStopAtFrame_3(event:MouseEvent):void
gotoAndStop(2);
/* Click to Go to Frame and Stop
Clicking on the specified symbol instance moves the playhead to the specified frame in the timeline and stops the movie.
Can be used on the main timeline or on movie clip timelines.
Instructions:
1. Replace the number 5 in the code below with the frame number you would like the playhead to move to when the symbol instance is clicked.
Help.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_4);
function fl_ClickToGoToAndStopAtFrame_4(event:MouseEvent):void
gotoAndStop(3);
/* Click to Go to Frame and Stop
Clicking on the specified symbol instance moves the playhead to the specified frame in the timeline and stops the movie.
Can be used on the main timeline or on movie clip timelines.
Instructions:
1. Replace the number 5 in the code below with the frame number you would like the playhead to move to when the symbol instance is clicked.
PlayButton.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame_12);
function fl_ClickToGoToAndStopAtFrame_12(event:MouseEvent):void
gotoAndStop(4);
/* Click to Go to Frame and Stop
Clicking on the specified symbol instance moves the playhead to the specified frame in the timeline and stops the movie.
Can be used on the main timeline or on movie clip timelines.
Instructions:
1. Replace the number 5 in the code below with the frame number you would like the playhead to move to when the symbol instance is clicked.
if(Ground.hitTestPoint(Char.x + leftBumpPoint.x, Char.y + leftBumpPoint.y, true)){
trace("leftBumping");
leftBumping = true;
} else {
leftBumping = false;
if(Ground.hitTestPoint(Char.x + rightBumpPoint.x, Char.y + rightBumpPoint.y, true)){
trace("rightBumping");
rightBumping = true;
} else {
rightBumping = false;
if(Ground.hitTestPoint(Char.x + upBumpPoint.x, Char.y + upBumpPoint.y, true)){
trace("upBumping");
upBumping = true;
} else {
upBumping = false;
if(Ground.hitTestPoint(Char.x + downBumpPoint.x, Char.y + downBumpPoint.y, true)){
trace("downBumping");
downBumping = true;
} else {
downBumping = false;
var leftBumping:Boolean = false;
var rightBumping:Boolean = false;
var upBumping:Boolean = false;
var downBumping:Boolean = false;
var leftBumpPoint:Point = new Point(-30, -55);
var rightBumpPoint:Point = new Point(30, -55);
var upBumpPoint:Point = new Point(0, -120);
var downBumpPoint:Point = new Point(0, 0);
/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.
Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
Char.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey_4);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed_4);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed_4);
function fl_MoveInDirectionOfKey_4(event:Event)
if (upPressed)
Char.y -= 0;
if (downPressed)
Char.y += 0;
if (leftPressed)
Char.x -= 0;
if (rightPressed)
Char.x += 0;
function fl_SetKeyPressed_4(event:KeyboardEvent):void
switch (event.keyCode)
case Keyboard.UP:
upPressed = true;
break;
case Keyboard.DOWN:
downPressed = true;
break;
case Keyboard.LEFT:
leftPressed = true;
break;
case Keyboard.RIGHT:
rightPressed = true;
break;
function fl_UnsetKeyPressed_4(event:KeyboardEvent):void
switch (event.keyCode)
case Keyboard.UP:
upPressed = false;
break;
case Keyboard.DOWN:
downPressed = false;
break;
case Keyboard.LEFT:
leftPressed = false;
break;
case Keyboard.RIGHT:
rightPressed = false;
break;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var xScrollSpeed:int = 10;
var yScrollSpeed:int = 10;
function keyDownHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
leftPressed = true;
} else if(e.keyCode == Keyboard.RIGHT){
rightPressed = true;
} else if(e.keyCode == Keyboard.UP){
upPressed = true;
} else if(e.keyCode == Keyboard.DOWN){
downPressed = true;
function keyUpHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.LEFT){
leftPressed = false;
} else if(e.keyCode == Keyboard.RIGHT){
rightPressed = false;
} else if(e.keyCode == Keyboard.UP){
upPressed = false;
} else if(e.keyCode == Keyboard.DOWN){
downPressed = false;
stage.addEventListener(Event.ENTER_FRAME, loop);
var scrollX:int = 0;
var scrollY:int = 0;
var ySpeed:int = 0;
var xSpeed:int = 0;
var speedConstant:int = 5;
var friction:Number = 0.95;
function loop(e:Event):void{
if(leftPressed){
xSpeed -= speedConstant;
} else if(rightPressed){
xSpeed += speedConstant;
if(upPressed){
ySpeed -= speedConstant;
} else if(downPressed){
ySpeed += speedConstant;
if(leftBumping){
if(xSpeed < 0){
xSpeed *= -0.5;
if(rightBumping){
if(xSpeed > 0){
xSpeed *= -0.5;
if(upBumping){
if(ySpeed < 0){
ySpeed *= -0.5;
if(downBumping){
if(ySpeed > 0){
ySpeed *= -0.5;
xSpeed *= friction;
ySpeed *= friction;
scrollX -= xSpeed;
scrollY -= ySpeed;
Ground.x = scrollX;
Ground.y = scrollY;click file>publish settings>swf and tick "permit debugging". retest.
the line number of the code that references a non-existant object will be in the error message.
if you need more help than that, indicate the copy and paste the error message and the line number referenced at the top of the error message. -
A litle help please... drawing app.
Hi all,
I'm trying to adapt a file I downloaded (legally) and I'm having some trouble as I'm still stuck in the days of AS2 and this has
been built in AS3. As you will see it's a drawing app that allows a few options for brush size, blur etc.,
What I'd like to do is to duplicate the brush_tool_mc with settings for full brush size and full blur to use as a spray can tool.
All my attempts so far have ended in disaster and multiple output errors ! : (
Any help / pointers / guidance much appreciated.
Best wishes
Tony
Source and example is here:
http://www.nocircleno.com/graffiti/examples/2.x/graffiti_advanced_demo.html
CODE: (Main.as)
* Example Application built with the Graffiti Library
* www.nocircleno.com/graffiti/
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
package {
import flash.display.Bitmap;
import flash.display.BitmapData
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.LineScaleMode;
import flash.display.CapsStyle;
import flash.display.JointStyle;
import flash.text.TextField;
import flash.geom.Point;
import flash.text.TextFormat;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.display.BlendMode;
import flash.net.navigateToURL;
import flash.net.FileReference;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLRequestHeader;
import flash.text.Font;
import flash.utils.ByteArray;
import fl.controls.CheckBox;
import fl.controls.ColorPicker;
import fl.controls.Slider;
import fl.controls.ComboBox;
import fl.events.ColorPickerEvent;
import fl.events.SliderEvent;
import fl.data.DataProvider;
import com.nocircleno.graffiti.GraffitiCanvas;
import com.nocircleno.graffiti.display.Text;
import com.nocircleno.graffiti.display.GraffitiObject;
import com.nocircleno.graffiti.events.CanvasEvent;
import com.nocircleno.graffiti.events.GraffitiObjectEvent;
import com.nocircleno.graffiti.tools.BrushTool;
import com.nocircleno.graffiti.tools.BrushType;
import com.nocircleno.graffiti.tools.LineTool;
import com.nocircleno.graffiti.tools.LineType;
import com.nocircleno.graffiti.tools.ShapeTool;
import com.nocircleno.graffiti.tools.ShapeType;
import com.nocircleno.graffiti.tools.ToolMode;
import com.nocircleno.graffiti.tools.ITool;
import com.nocircleno.graffiti.tools.BitmapTool;
import com.nocircleno.graffiti.tools.FillBucketTool;
import com.nocircleno.graffiti.tools.SelectionTool;
import com.nocircleno.graffiti.tools.TextSettings;
import com.nocircleno.graffiti.tools.TextTool;
import com.nocircleno.graffiti.managers.GraffitiObjectManager;
import com.adobe.images.PNGEncoder;
public class Main extends MovieClip {
public var click_message_txt:TextField;
// ui
public var brush_tool_mc:ItemButton;
public var eraser_tool_mc:ItemButton;
public var line_tool_mc:ItemButton;
public var rectangle_tool_mc:ItemButton;
public var fillbucket_tool_mc:ItemButton;
public var selection_tool_mc:ItemButton;
public var text_tool_mc:ItemButton;
public var oval_tool_mc:ItemButton;
public var clear_btn:SimpleButton;
public var save_btn:SimpleButton;
public var undo_btn:SimpleButton;
public var redo_btn:SimpleButton;
public var slider_label_txt:TextField;
public var slider_2_label_txt:TextField;
public var slider_3_label_txt:TextField;
public var combo_label_txt:TextField;
public var stroke_color_mc:ColorPicker;
public var fill_color_mc:ColorPicker;
public var slider_mc:Slider;
public var slider_2_mc:Slider;
public var slider_3_mc:Slider;
public var zoom_slider_mc:Slider;
public var combo_list:ComboBox;
public var overlay_cb:CheckBox;
public var overlay_mc:MovieClip;
public var canvas:GraffitiCanvas;
public var border:Sprite;
// tools
private var _brush:BrushTool;
private var _eraser:BrushTool;
private var _line:LineTool;
private var _shape:ShapeTool;
private var _selectionTool:SelectionTool;
private var _textTool:TextTool;
private var _fillBucketTool:FillBucketTool;
// props
private var _brushSize:Number = 2;
private var _strokeColor:uint = 0x00FF00;
private var _fillColor:uint = 0xFF0000;
private var _strokeAlpha:Number = 1;
private var _fillAlpha:Number = 1;
private var _brushBlur:Number = 0;
private var _fontColor:uint = 0x00FF00;
private var _fontSize:uint = 14;
private var _brushShapeIndex:int;
private var _lineStyleIndex:int;
private var _fontIndex:uint = 0;
private var _fontList:DataProvider;
private var _brushShapes:DataProvider;
private var _lineStyles:DataProvider;
private var _fileRef:FileReference;
private var _objectManager:GraffitiObjectManager;
private var _orginalComboBoxItemsPos = new Object();
public function Main() {
// hide message
click_message_txt.alpha = 0;
// create canvas
canvas = new GraffitiCanvas(840, 470, 10);
canvas.x = 0;
canvas.y = 120;
canvas.addEventListener(MouseEvent.MOUSE_WHEEL, scrollHandler);
canvas.addEventListener(GraffitiCanvas.HISTORY_LENGTH_CHANGE, historyLengthChangeHandler);
canvas.addEventListener(GraffitiObjectEvent.SELECT, objectEventHandler);
canvas.addEventListener(GraffitiObjectEvent.ENTER_EDIT, objectEventHandler);
addChild(canvas);
// add image over canvas
overlay_mc = new OverlayImage();
canvas.overlay = overlay_mc;
// get instance of graffiti object manager
_objectManager = GraffitiObjectManager.getInstance();
// add listeners for keyboard shortcuts
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
// add event listeners for tool buttons
selection_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
text_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
fillbucket_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
brush_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
eraser_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
line_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
rectangle_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
oval_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
// setup data providers
_brushShapes = new DataProvider();
_brushShapes.addItem({label:"Round", data: BrushType.ROUND});
_brushShapes.addItem({label:"Square", data: BrushType.SQUARE});
_brushShapes.addItem({label:"Diamond", data: BrushType.DIAMOND});
_brushShapes.addItem({label:"Vertical", data: BrushType.VERTICAL_LINE});
_brushShapes.addItem({label:"Horizontal", data: BrushType.HORIZONTAL_LINE});
_brushShapes.addItem({label:"Forward", data: BrushType.FORWARD_LINE});
_brushShapes.addItem({label:"Backward", data: BrushType.BACKWARD_LINE});
_lineStyles = new DataProvider();
_lineStyles.addItem({label:"Solid", data: LineType.SOLID});
_lineStyles.addItem({label:"Dotted", data: LineType.DOTTED});
_lineStyles.addItem( { label:"Dashed", data: LineType.DASHED } );
// Setup Font List
_fontList = new DataProvider();
var embeddedFonts:Array = Font.enumerateFonts(true);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
for (var i:int = 0; i < embeddedFonts.length; i++) {
_fontList.addItem( {label: embeddedFonts[i].fontName, data: embeddedFonts[i] } );
// create tool instances
_brush = new BrushTool(_brushSize, _fillColor, _fillAlpha, _brushBlur, BrushType.ROUND);
_eraser = new BrushTool(_brushSize, _fillColor, 1, _brushBlur, BrushType.ROUND, ToolMode.ERASE);
_line = new LineTool(2, _strokeColor, _strokeAlpha, LineType.SOLID);
_shape = new ShapeTool(2, _strokeColor, _fillColor, _strokeAlpha, _fillAlpha, ShapeType.RECTANGLE);
_fillBucketTool = new FillBucketTool(_fillColor, true);
_selectionTool = new SelectionTool();
_textTool = new TextTool(new TextSettings(Font(_fontList.getItemAt(0).data), new TextFormat(null, _fontSize, _fontColor)));
// setup color pickers
stroke_color_mc.focusEnabled = false;
stroke_color_mc.selectedColor = _strokeColor;
stroke_color_mc.addEventListener(ColorPickerEvent.CHANGE, colorPickerHandler);
stroke_color_mc.enabled = false;
fill_color_mc.focusEnabled = false;
fill_color_mc.selectedColor = _fillColor;
fill_color_mc.addEventListener(ColorPickerEvent.CHANGE, colorPickerHandler);
slider_mc.addEventListener(SliderEvent.CHANGE, sliderHandler);
slider_2_mc.addEventListener(SliderEvent.CHANGE, sliderHandler);
slider_3_mc.addEventListener(SliderEvent.CHANGE, sliderHandler);
overlay_cb.addEventListener(Event.CHANGE, overlayHandler);
overlay_cb.focusEnabled = false;
// config combo list
combo_list.addEventListener(Event.CHANGE, comboEventHandler);
combo_list.dataProvider = _brushShapes;
combo_list.focusEnabled = false;
// store positions
_orginalComboBoxItemsPos.comboBox = new Point(combo_list.x, combo_list.y);
_orginalComboBoxItemsPos.comboBoxLabel = new Point(combo_label_txt.x, combo_label_txt.y);
// disable undo and redo buttons
undo_btn.mouseEnabled = false;
undo_btn.alpha = .5;
redo_btn.mouseEnabled = false;
redo_btn.alpha = .5;
// add event listeners
undo_btn.addEventListener(MouseEvent.CLICK, historyHandler);
redo_btn.addEventListener(MouseEvent.CLICK, historyHandler);
clear_btn.addEventListener(MouseEvent.CLICK, clearCanvasHandler);
save_btn.addEventListener(MouseEvent.CLICK, saveHandler);
zoom_slider_mc.maximum = canvas.maxZoom;
zoom_slider_mc.addEventListener(SliderEvent.CHANGE, zoomHandler);
// assign the brush tool as the default tool
canvas.activeTool = _brush;
// set brush tool
brush_tool_mc.selected = true;
setSelectedBrushShape(BrushType.ROUND);
Method : objectEventHandler()
Purpose : This method handles GraffitiObjectEvents. We use this
to know when an object is selected or enters edit mode.
Params : e -- GraffitiObjectEvent object.
private function objectEventHandler(e:GraffitiObjectEvent):void {
var font:Font;
var fmt:TextFormat;
var i:int;
if (e.type == GraffitiObjectEvent.SELECT) {
// get font and text format of selected object
font = Text(e.graffitiObject).textSetting.font;
fmt = Text(e.graffitiObject).textSetting.textFormat;
_fontSize = Number(fmt.size);
var fontFromList:Font;
var numberFonts:uint = _fontList.length;
// find select text font in font list
for (i = 0; i < numberFonts; i++) {
fontFromList = Font(_fontList.getItemAt(i).data);
if (fontFromList.fontName == font.fontName && fontFromList.fontStyle == font.fontStyle) {
_fontIndex = i;
break;
// if text tool is active tool, then update it.
if (canvas.activeTool is TextTool) {
TextTool(canvas.activeTool).textSettings = new TextSettings(font, fmt);
} else {
_textTool.textSettings.textFormat.size = Number(fmt.size);
// update ui for objects
combo_list.selectedIndex = _fontIndex;
slider_mc.value = Number(fmt.size);
fill_color_mc.selectedColor = uint(fmt.color);
} else if (e.type == GraffitiObjectEvent.ENTER_EDIT) {
// if we enter edit mode on an text object, make sure the tool is set to the text tool.
if (e.graffitiObject is Text && !(canvas.activeTool is TextTool)) {
setActiveTool(text_tool_mc);
Method : overlayHandler()
Purpose : This method toggles the overlay on and off.
Params : e -- Event object.
private function overlayHandler(e:Event):void {
if(e.currentTarget.selected) {
canvas.overlay = overlay_mc;
} else {
canvas.overlay = null;
Method : historyHandler()
Purpose : This method undo or redo the drawing depending on the button
clicked by the user.
Params : e -- MouseEvent object.
private function historyHandler(e:MouseEvent):void {
if(e.currentTarget == undo_btn) {
canvas.prevHistory();
if(canvas.historyPosition == 0) {
undo_btn.mouseEnabled = false;
undo_btn.alpha = .5;
redo_btn.mouseEnabled = true;
redo_btn.alpha = 1;
} else if(e.currentTarget == redo_btn) {
canvas.nextHistory();
if(canvas.historyPosition == (canvas.historyLength - 1)) {
redo_btn.mouseEnabled = false;
redo_btn.alpha = .5;
undo_btn.mouseEnabled = true;
undo_btn.alpha = 1;
Method : clearCanvasHandler()
Purpose : This method will clear the canvas.
Params : e -- MouseEvent object.
private function clearCanvasHandler(e:MouseEvent):void {
canvas.clearCanvas();
Method : saveHandler()
Purpose : This method will save the drawing as a PNG image.
Params : e -- MouseEvent object.
private function saveHandler(e:MouseEvent):void {
// get drawing as bitmapdata from the Graffiti Canvas instance.
var canvasBmp:BitmapData = canvas.drawing();
// create new jpg encoder object and convert bitmapdata to jpg
var pngEncoder:PNGEncoder = new PNGEncoder();
var pngStream:ByteArray = PNGEncoder.encode(canvasBmp);
// make sure you dispose of the bitmapdata object when finished.
canvasBmp.dispose();
_fileRef = new FileReference();
_fileRef.save(pngStream, "graffiti_example_image.png");
Method : historyLengthChangeHandler()
Purpose : This method will handle the change in the number of stored
history items. This is used to toggle the redo and undo
buttons.
Params : e -- Event object.
private function historyLengthChangeHandler(e:Event):void {
if(canvas.historyLength > 0 && canvas.historyPosition != 0) {
undo_btn.mouseEnabled = true;
undo_btn.alpha = 1;
} else {
undo_btn.mouseEnabled = false;
undo_btn.alpha = .5;
if(canvas.historyLength > 0 && canvas.historyPosition != canvas.historyLength - 1) {
redo_btn.mouseEnabled = true;
redo_btn.alpha = 1;
} else {
redo_btn.mouseEnabled = false;
redo_btn.alpha = .5;
Method : zoomHandler()
Purpose : This method will handle the zoom slider event and set the
canvas to the new zoom level.
Params : e -- SliderEvent object.
private function zoomHandler(e:SliderEvent):void {
// set zoom of canvas
canvas.zoom = e.value;
// if canvas is zoomed in then display message about dragging canvas with mouse.
if(canvas.zoom > 1) {
click_message_txt.alpha = 1;
} else {
click_message_txt.alpha = 0;
Method : colorPickerHandler()
Purpose : This method will handle the color picker event.
Params : e -- ColorPickerEvent object.
private function colorPickerHandler(e:ColorPickerEvent):void {
var font:Font;
var fmt:TextFormat;
var ts:TextSettings;
if(canvas.activeTool is BrushTool) {
_fillColor = e.color;
BrushTool(canvas.activeTool).color = _fillColor;
} else if(canvas.activeTool is LineTool) {
_strokeColor = e.color;
LineTool(canvas.activeTool).color = _strokeColor;
} else if(canvas.activeTool is ShapeTool) {
if(e.currentTarget == stroke_color_mc) {
_strokeColor = e.color;
ShapeTool(canvas.activeTool).strokeColor = _strokeColor;
} else if (e.currentTarget == fill_color_mc) {
_fillColor = e.color;
ShapeTool(canvas.activeTool).fillColor = _fillColor;
} else if (canvas.activeTool is TextTool) {
// update color of textformat object
fmt = TextTool(canvas.activeTool).textSettings.textFormat;
fmt.color = fill_color_mc.selectedColor;
// update text tool
TextTool(canvas.activeTool).textSettings.textFormat = fmt;
// update any selected text with new color
if (_objectManager.areObjectsSelected()) {
font = Font(combo_list.selectedItem.data);
fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
ts = new TextSettings(font, fmt);
_objectManager.changeSettingsForSelectedObjects(ts);
} else if (canvas.activeTool is SelectionTool) {
font = Font(combo_list.selectedItem.data);
fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
ts = new TextSettings(font, fmt);
// update text tool
_textTool.textSettings = ts;
if (_objectManager.areObjectsSelected()) {
// change settings for selected text
_objectManager.changeSettingsForSelectedObjects(ts);
} else if (canvas.activeTool is FillBucketTool) {
FillBucketTool(canvas.activeTool).fillColor = fill_color_mc.selectedColor;
Method : sliderHandler()
Purpose : This method will handle the slider change.
Params : e -- SliderEvent object.
private function sliderHandler(e:SliderEvent):void {
var font:Font;
var fmt:TextFormat;
var ts:TextSettings;
if(e.currentTarget == slider_mc) {
if(canvas.activeTool == _brush || canvas.activeTool == _eraser) {
_brushSize = e.value;
BrushTool(canvas.activeTool).size = _brushSize;
} else if(canvas.activeTool == _line) {
LineTool(canvas.activeTool).lineWidth = e.value;
} else if(canvas.activeTool == _shape) {
ShapeTool(canvas.activeTool).strokeWidth = e.value;
} else if (canvas.activeTool is TextTool) {
_fontSize = slider_mc.value;
fmt = TextTool(canvas.activeTool).textSettings.textFormat;
fmt.size = slider_mc.value;
TextTool(canvas.activeTool).textSettings.textFormat = fmt;
if (_objectManager.areObjectsSelected()) {
font = Font(combo_list.selectedItem.data);
fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
ts = new TextSettings(font, fmt);
_objectManager.changeSettingsForSelectedObjects(ts);
} else if (canvas.activeTool == _selectionTool) {
_fontSize = slider_mc.value;
font = Font(combo_list.selectedItem.data);
fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
ts = new TextSettings(font, fmt);
// update text tool
_textTool.textSettings = ts;
if (_objectManager.areObjectsSelected()) {
_objectManager.changeSettingsForSelectedObjects(ts);
} else if(e.currentTarget == slider_2_mc) {
if(canvas.activeTool is BrushTool) {
_fillAlpha = e.value;
BrushTool(canvas.activeTool).alpha = e.value;
} else if (canvas.activeTool is LineTool) {
_strokeAlpha = e.value;
LineTool(canvas.activeTool).alpha = e.value;
} else if (canvas.activeTool is ShapeTool) {
_strokeAlpha = e.value;
ShapeTool(canvas.activeTool).strokeAlpha = e.value;
} else if(e.currentTarget == slider_3_mc) {
if(canvas.activeTool is BrushTool) {
_brushBlur = e.value;
BrushTool(canvas.activeTool).blur = e.value;
} else if(canvas.activeTool is ShapeTool) {
_fillAlpha = e.value;
ShapeTool(canvas.activeTool).fillAlpha = e.value;
Method : setActiveTool()
Purpose : This method sets the program to use a new tool.
Params : toolButton -- One of the Tool Buttons.
private function setActiveTool(toolButton:ItemButton):void {
// deselect all button to start
brush_tool_mc.selected = false;
eraser_tool_mc.selected = false;
line_tool_mc.selected = false;
rectangle_tool_mc.selected = false;
oval_tool_mc.selected = false;
selection_tool_mc.selected = false;
fillbucket_tool_mc.selected = false;
text_tool_mc.selected = false;
// show combo box
combo_label_txt.visible = true;
combo_list.visible = true;
combo_list.x = _orginalComboBoxItemsPos.comboBox.x;
combo_list.y = _orginalComboBoxItemsPos.comboBox.y;
combo_label_txt.x = _orginalComboBoxItemsPos.comboBoxLabel.x;
combo_label_txt.y = _orginalComboBoxItemsPos.comboBoxLabel.y;
// set slider
slider_mc.minimum = 2;
slider_mc.maximum = 40;
// enable all slider ui
slider_mc.visible = true;
slider_label_txt.visible = true;
slider_2_label_txt.visible = true;
slider_2_mc.visible = true;
slider_3_label_txt.visible = true;
slider_3_mc.visible = true;
slider_2_label_txt.alpha = 1;
// make sure both color pickers are enabled at this point.
// let each tool block decide to turn them off.
fill_color_mc.enabled = true;
stroke_color_mc.enabled = true;
// brush tool selected
if(toolButton == brush_tool_mc) {
// set selected tool state
brush_tool_mc.selected = true;
// config color pickers
stroke_color_mc.enabled = false;
// set brush shape list
combo_label_txt.text = "Brush Shapes";
combo_list.dataProvider = _brushShapes;
combo_list.selectedIndex = _brushShapeIndex;
// config and set brush tool as active tool
_brush.color = fill_color_mc.selectedColor;
_brush.alpha = _fillAlpha;
_brush.blur = _brushBlur;
_brush.size = _brushSize;
_brush.type = combo_list.selectedItem.data;
canvas.activeTool = _brush;
// update slider
slider_label_txt.text = "Brush Size";
slider_mc.value = _brush.size;
slider_2_label_txt.text = "Brush Alpha";
slider_2_label_txt.alpha = 1;
slider_2_mc.enabled = true;
slider_2_mc.snapInterval = .1;
slider_2_mc.value = _brush.alpha;
slider_3_label_txt.text = "Brush Blur";
slider_3_label_txt.visible = true;
slider_3_label_txt.alpha = 1;
slider_3_mc.visible = true;
slider_3_mc.snapInterval = 1;
slider_3_mc.enabled = true;
slider_3_mc.minimum = 0;
slider_3_mc.maximum = 20;
slider_3_mc.value = _brush.blur;
// eraser tool selected
} else if(toolButton == eraser_tool_mc) {
// set selected tool state
eraser_tool_mc.selected = true;
// config color picker
fill_color_mc.enabled = false;
stroke_color_mc.enabled = false;
// set brush shape list
combo_label_txt.text = "Brush Shapes";
combo_list.dataProvider = _brushShapes;
combo_list.selectedIndex = _brushShapeIndex;
// config and set eraser tool as active tool
_eraser.color = fill_color_mc.selectedColor;
_brush.alpha = 1;
_brush.blur = _brushBlur;
_eraser.size = _brushSize;
_eraser.type = combo_list.selectedItem.data;
canvas.activeTool = _eraser;
// update slider
slider_label_txt.text = "Brush Size";
slider_mc.value = _eraser.size;
slider_2_label_txt.text = "Brush Alpha";
slider_2_label_txt.alpha = .5;
slider_2_mc.enabled = false;
slider_2_mc.snapInterval = .1;
slider_2_mc.value = _eraser.alpha;
slider_3_label_txt.text = "Brush Blur";
slider_3_label_txt.visible = true;
slider_3_label_txt.alpha = .5;
slider_3_mc.visible = true;
slider_3_mc.minimum = 0;
slider_3_mc.maximum = 20;
slider_3_mc.enabled = false;
slider_3_mc.value = _eraser.blur;
// line tool
} else if(toolButton == line_tool_mc) {
// set selected tool state
line_tool_mc.selected = true;
// config color picker
fill_color_mc.enabled = false;
// set line style list
combo_label_txt.text = "Line Style";
combo_list.dataProvider = _lineStyles;
combo_list.selectedIndex = _lineStyleIndex;
combo_label_txt.x = slider_3_label_txt.x + 8;
combo_list.x = slider_3_mc.x;
// config and set line tool as active tool
_line.color = stroke_color_mc.selectedColor;
_line.alpha = _strokeAlpha;
_line.type = combo_list.selectedItem.data;
canvas.activeTool = _line;
// update slider
slider_label_txt.text = "Stroke Size";
slider_mc.value = _line.lineWidth;
slider_2_label_txt.text = "Line Alpha";
slider_2_mc.enabled = true;
slider_2_mc.snapInterval = .1;
slider_2_mc.value = _line.alpha;
slider_3_label_txt.visible = false;
slider_3_mc.visible = false;
// rectangle tool
} else if(toolButton == rectangle_tool_mc) {
// set selected tool state
rectangle_tool_mc.selected = true;
// config and set shape tool as active tool
_shape.strokeColor = stroke_color_mc.selectedColor;
_shape.fillColor = fill_color_mc.selectedColor;
_shape.strokeAlpha = _strokeAlpha;
_shape.fillAlpha = _fillAlpha;
_shape.type = ShapeType.RECTANGLE;
canvas.activeTool = _shape;
// set slide value
slider_label_txt.text = "Stroke Size";
slider_mc.value = _shape.strokeWidth;
slider_2_label_txt.text = "Stroke Alpha";
slider_2_label_txt.alpha = 1;
slider_2_mc.enabled = true;
slider_2_mc.snapInterval = .1;
slider_2_mc.value = _shape.strokeAlpha;
slider_3_label_txt.text = "Fill Alpha";
slider_3_label_txt.visible = true;
slider_3_label_txt.alpha = 1;
slider_3_mc.visible = true;
slider_3_mc.enabled = true;
slider_3_mc.minimum = 0;
slider_3_mc.maximum = 1;
slider_3_mc.snapInterval = .1;
slider_3_mc.value = _shape.fillAlpha;
// hide combo box
combo_label_txt.visible = false;
combo_list.visible = false;
// oval tool
} else if(toolButton == oval_tool_mc) {
// set selected tool state
oval_tool_mc.selected = true;
// config and set shape tool as active tool
_shape.strokeColor = stroke_color_mc.selectedColor;
_shape.fillColor = fill_color_mc.selectedColor;
_shape.strokeAlpha = _strokeAlpha;
_shape.fillAlpha = _fillAlpha;
_shape.type = ShapeType.OVAL;
canvas.activeTool = _shape;
// update slider
slider_label_txt.text = "Stroke Size";
slider_mc.value = _shape.strokeWidth;
slider_2_label_txt.text = "Stroke Alpha";
slider_2_label_txt.alpha = 1;
slider_2_mc.enabled = true;
slider_2_mc.snapInterval = .1;
slider_2_mc.value = _shape.strokeAlpha;
slider_3_label_txt.text = "Fill Alpha";
slider_3_label_txt.visible = true;
slider_3_label_txt.alpha = 1;
slider_3_mc.visible = true;
slider_3_mc.enabled = true;
slider_3_mc.minimum = 0;
slider_3_mc.maximum = 1;
slider_3_mc.snapInterval = .1;
slider_3_mc.value = _shape.fillAlpha;
// hide combo box
combo_label_txt.visible = false;
combo_list.visible = false;
// text tool selected
} else if (toolButton == text_tool_mc || toolButton == selection_tool_mc) {
// disable stroke color picker
stroke_color_mc.enabled = false;
// ui for text
slider_label_txt.text = "Text Size";
// set font style list
combo_label_txt.text = "Font";
combo_list.dataProvider = _fontList;
combo_list.selectedIndex = _fontIndex;
// turn off ui not needed for text tool
slider_2_label_txt.visible = false;
slider_2_mc.visible = false;
slider_3_label_txt.visible = false;
slider_3_mc.visible = false;
combo_label_txt.x = slider_2_label_txt.x + 8;
combo_list.x = slider_2_mc.x;
slider_mc.minimum = 10;
slider_mc.maximum = 44;
slider_mc.value = Number(_textTool.textSettings.textFormat.size);
if (toolButton == selection_tool_mc) {
selection_tool_mc.selected = true;
// set active tool
canvas.activeTool = _selectionTool;
} else {
text_tool_mc.selected = true;
var font:Font = Font(combo_list.selectedItem.data);
var fmt:TextFormat = new TextFormat();
fmt.size = slider_mc.value;
fmt.color = fill_color_mc.selectedColor;
_textTool.textSettings = new TextSettings(font, fmt);
// set active tool
canvas.activeTool = _textTool;
// fill bucket tool selected
} else if (toolButton == fillbucket_tool_mc) {
// turn off ui not needed for fill bucket tool
slider_mc.visible = false;
slider_label_txt.visible = false;
slider_2_label_txt.visible = false;
slider_2_mc.visible = false;
slider_3_label_txt.visible = false;
slider_3_mc.visible = false;
combo_label_txt.visible = false;
combo_list.visible = false;
// turn off stroke color picker
this.stroke_color_mc.enabled = false;
this._fillBucketTool.fillColor = fill_color_mc.selectedColor;
fillbucket_tool_mc.selected = true;
// set active tool
canvas.activeTool = _fillBucketTool;
Method : toolHandler()
Purpose : This method will handle switching between brush and eraser
tools. The two tool buttons call this method on click.
Params : e -- Mouse Event object.
private function toolHandler(e:MouseEvent):void {
setActiveTool(ItemButton(e.currentTarget));
Method : comboEventHandler()
Purpose : This method will handle the button events for the different
Combo box in the UI.
Params : e -- Mouse Event object.
private function comboEventHandler(e:Event):void {
var font:Font;
var fmt:TextFormat;
var ts:TextSettings;
if(canvas.activeTool is BrushTool) {
// store brush shape index
_brushShapeIndex = ComboBox(e.currentTarget).selectedIndex;
setSelectedBrushShape(ComboBox(e.currentTarget).selectedItem.data);
} else if(canvas.activeTool is LineTool) {
// store line style index
_lineStyleIndex = ComboBox(e.currentTarget).selectedIndex;
setSelectedLineStyle(ComboBox(e.currentTarget).selectedItem.data);
} else if (canvas.activeTool is TextTool) {
// update font for text tool
font = Font(combo_list.selectedItem.data);
TextTool(canvas.activeTool).textSettings.font = font;
// update font index
_fontIndex = combo_list.selectedIndex;
// update font for any selected text
if (_objectManager.areObjectsSelected()) {
fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
ts = new TextSettings(font, fmt);
_objectManager.changeSettingsForSelectedObjects(ts);
} else if (canvas.activeTool is SelectionTool) {
font = Font(combo_list.selectedItem.data);
fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
ts = new TextSettings(font, fmt);
// update font index
_fontIndex = combo_list.selectedIndex;
// update text tool
_textTool.textSettings = ts;
// update font for any selected text
if (_objectManager.areObjectsSelected()) {
_objectManager.changeSettingsForSelectedObjects(ts);
Method : setSelectedLineStyle()
Purpose : This method will update the active line with a new line
type.
Params : localType -- Type of Line.
private function setSelectedLineStyle(localType:String):void {
// update the Brush object if different type
if(BitmapTool(canvas.activeTool).type != localType) {
BitmapTool(canvas.activeTool).type = localType;
Method : setSelectedBrushShape()
Purpose : This method will update the active brush with a new brush
type.
Params : localType -- Type of Brush.
private function setSelectedBrushShape(localType:String):void {
// update the Brush object if different type
if(BitmapTool(canvas.activeTool).type != localType) {
BitmapTool(canvas.activeTool).type = localType;
Method : scrollHandler()
Purpose : This method handles the event from the mouse scroll wheel.
Params : e -- MouseEvent object
public function scrollHandler(e:MouseEvent):void {
// calculate and set zoom of canvas
canvas.zoom += (e.delta/3) * 1;
// sync slider to new zoom value.
zoom_slider_mc.value = canvas.zoom;
// if canvas is zoomed in then display message about dragging canvas around.
if(canvas.zoom > 1) {
click_message_txt.alpha = 1;
} else {
click_message_txt.alpha = 0;
Method : keyHandler()
Purpose : This method handle the keyboard shortcut to drag allow
the user to drag the canvas with their mouse.
Params : e -- KeyboardEvent object
public function keyHandler(e:KeyboardEvent):void {
if(!_objectManager.areObjectsSelected()) {
if(e.keyCode == Keyboard.SPACE) {
if(e.type == KeyboardEvent.KEY_UP) {
canvas.mouseDrag = false;
} else if(e.type == KeyboardEvent.KEY_DOWN) {
canvas.mouseDrag = true;
This might be outdated since the discount is applied to the access portion and accessories only now.
Verizon Corporate Discount List - HowardForums Wiki
Verizon Employee Discount List for 2015 -
Sound not working in Flash Builder. Help please.
So, here's my situation. I keep trying to put an mp3 in Flash Builder to try and make sounds happen, but each time I do it only plays the beginning of it and stops midway through. My music is working at 44100 Hz with a 32 bit rate (tried changing it to 16, but Audition won't let me). Here's my code.
package
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.ui.Keyboard;
[SWF(width = "550", height = "400",
backgroundColor = "#FFFFFF", frameRate = "60")]
public class SoundThing extends Sprite
[Embed(source="../sounds/try1.mp3")]
private var Try:Class;
private var _try:Sound = new Try();
private var _tryChannel:SoundChannel = new SoundChannel();
public function SoundThing()
stage.addEventListener
(KeyboardEvent.KEY_DOWN, keyDownHandler);
public function keyDownHandler(event:KeyboardEvent): void
if (event.keyCode == Keyboard.SPACE)
_tryChannel = _try.play();
I'm not sure what the issue is. Please help me. Thank you!I would say that either the OP needs two tabs somewhere to make his headings and line items align,Exactly what I was thinking. As this sample code illustrates, the b will not line up under Column#2. Perhpas OP needs to use a Formatter or the printf method instead.
StringBuffer sb = new StringBuffer();
sb.append("Column#1");
sb.append("\tColumn#2\n");
sb.append("a");
sb.append("\t");
sb.append("b");
System.out.println(sb); -
Hi guys , just joined!!!
I am a PHP developer and have 'forced' into some work with java.
Now I am a complete noob here and I have what I hope is a fairly straight forward request. I have a jar file that I have extracted so I can view all teh classess witihin and have found a class decompiler so I can actually see the code.
I need to edit one of the classes and then re-generate the .jar file.
What software do I need (just got the java studio creator and java studio enterprise...) and how exactly do I go about this process.
I have read a few pages abut this but still not confident so would really appreciate a hand holding exercise if anyone wuld be so kind.Hello! There seems to be alot wrong, so I don't know if I'll
get you up and running, but I'll try.
First of all you are stating "override function" for the
first 2 functions. This is only ok when you use it inside a class
(I assume you are coding on the timeline right?), so get rid of the
override.
Secondly I am not really sure what you are trying to do with
this part of your code:
addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
keyDownHandler {function event
(keyCode)==Keyboard.LEFT):void;{
gotoAndStop:(20);
addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler2);
keyDownHandler2(event )(keyCode==Keyboard.RIGHT);{
gotoAndStop:(30);
Are you trying to specify another 2 functions (you'll have a
naming conflict then as keyDownHandler and keyDownHandler2 are
already in use) or are you trying to call the above functions?
Third there are little flaws like gotoAndStop:(30); which
should be gotoAndStop(30); and some semicolons too much.
Hope that helps a little. -
I can't solve this for days already... When the hero object dies, the floorObject do not remove completely, such that one of them remains. And the hero object
disappears. Thanks for all the help.
package
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.events.*;
import flash.utils.getTimer;
public class Platform extends MovieClip
// movement constants
static const gravity:Number = .004;
// screen constants
static const edgeDistance:Number = 100;
// object arrays
private var fixedObjects:Array;
private var otherObjects:Array;
// hero and enemies
private var hero:Object;
private var enemies:Array;
// game state
private var playerObjects:Array;
private var gameScore:int;
private var gameMode:String = "start";
private var playerLives:int;
private var lastTime:Number = 0;
private var currentX:int = 0;
public function startPlatformGame()
// constructor code
gameMode = "play";
public function startGameLevel()
createHero();
addEnemies();
// examine level and note all objects
examineLevel();
// add listeners
this.addEventListener(Event.ENTER_FRAME,gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.addEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
// set game state
gameMode = "play";
public function createHero()
hero = new Object();
hero.mc = gamelevel.hero;
hero.dx = 0.0;
hero.dy = 0.0;
hero.inAir = false;
hero.direction = 1;
hero.animstate = "stand";
hero.walkAnimation = new Array(2,3,4,5,6,7,8);
hero.animstep = 0;
hero.jump = false;
hero.moveLeft = false;
hero.moveRight = true;
hero.jumpSpeed = .8;
hero.walkSpeed = .15;
hero.width = 30.0;
hero.height = 40.0;
hero.startx = hero.mc.x;
hero.starty = hero.mc.y;
public function addEnemies() {
enemies = new Array();
var i:int = 1;
while (true) {
if (gamelevel["enemy"+i] == null) break;
var enemy = new Object();
enemy.mc = gamelevel["enemy"+i];
enemy.dx = 0.0;
enemy.dy = 0.0;
enemy.inAir = false;
enemy.direction = 1;
enemy.animstate = "stand"
enemy.walkAnimation = new Array(2,3,4,5);
enemy.animstep = 0;
enemy.jump = false;
enemy.moveRight = true;
enemy.moveLeft = false;
enemy.jumpSpeed = 1.0;
enemy.walkSpeed = .08;
enemy.width = 30.0;
enemy.height = 30.0;
enemies.push(enemy);
i++;
public function examineLevel()
fixedObjects = new Array();
otherObjects = new Array();
for (var i:int=0; i<this.gamelevel.numChildren; i++)
var mc = this.gamelevel.getChildAt(i);
// add floors and walls to fixedObjects
if (mc is Floor)
var floorObject:Object = new Object();
floorObject.mc = mc;
floorObject.leftside = mc.x;
floorObject.rightside = mc.x + mc.width;
floorObject.topside = mc.y;
floorObject.bottomside = mc.y + mc.height;
fixedObjects.push(floorObject);
else if ((mc is Treasure) )
otherObjects.push(mc);
fixedObjects.sortOn("leftside" , Array.NUMERIC );
for each (floorObject in fixedObjects)
trace(floorObject.leftside);
// add treasure, key and door to otherOjects;
public function keyDownFunction(event:KeyboardEvent)
if (gameMode != "play")
return;
}// don't move until in play mode
if (event.keyCode == 37)
hero.moveLeft = true;
else if (event.keyCode == 39)
hero.moveRight = true;
else if (event.keyCode == 32)
if (! hero.inAir)
hero.jump = true;
public function keyUpFunction(event:KeyboardEvent)
if (event.keyCode == 37)
hero.moveLeft = false;
else if (event.keyCode == 39)
hero.moveRight = false;
public function gameLoop(event:Event)
// get time differentce
if (lastTime == 0)
lastTime = getTimer();
var timeDiff:int = getTimer() - lastTime;
lastTime += timeDiff;
// only perform tasks if in play mode
if (gameMode == "play")
moveCharacter(hero,timeDiff);
checkCollisions();
scrollWithHero();
death();
public function moveCharacter(char:Object,timeDiff:Number)
if (timeDiff < 1)
return;
// assume character pulled down by gravity
var verticalChange:Number = char.dy * timeDiff + timeDiff * gravity;
if (verticalChange > 15.0)
verticalChange = 15.0;
char.dy += timeDiff * gravity;
// react to changes from key presses
var horizontalChange = 0;
var newAnimState:String = "stand";
var newDirection:int = char.direction;
if (char.moveLeft)
// walk left
horizontalChange = - char.walkSpeed * timeDiff;
newAnimState = "walk";
newDirection = -1;
else if (char.moveRight)
// walk right
horizontalChange = char.walkSpeed * timeDiff;
newAnimState = "walk";
newDirection = 1;
if (char.jump)
// start jump
char.jump = false;
char.dy = - char.jumpSpeed;
verticalChange = - char.jumpSpeed;
newAnimState = "jump";
// assume no wall hit, and hanging in air
char.hitWallRight = false;
char.hitWallLeft = false;
char.inAir = true;
// find new vertical position
var newY:Number = char.mc.y + verticalChange;
// loop through all fixed objects to see if character has landed
for (var i:int=0; i<fixedObjects.length; i++)
if ((char.mc.x+char.width/2 > fixedObjects[i].leftside) && (char.mc.x-char.width/2 < fixedObjects[i].rightside))
if ((char.mc.y <= fixedObjects[i].topside) && (newY > fixedObjects[i].topside))
newY = fixedObjects[i].topside;
char.dy = 0;
char.inAir = false;
break;
// find new horizontal position
var newX:Number = char.mc.x + horizontalChange;
// loop through all objects to see if character has bumped into a wall
for (i=0; i<fixedObjects.length; i++)
if ((newY > fixedObjects[i].topside) && (newY-char.height < fixedObjects[i].bottomside))
if ((char.mc.x-char.width/2 >= fixedObjects[i].rightside) && (newX-char.width/2 <= fixedObjects[i].rightside))
newX = fixedObjects[i].rightside + char.width / 2;
char.hitWallLeft = true;
break;
if ((char.mc.x+char.width/2 <= fixedObjects[i].leftside) && (newX+char.width/2 >= fixedObjects[i].leftside))
newX = fixedObjects[i].leftside - char.width / 2;
char.hitWallRight = true;
break;
// set position of character
char.mc.x = newX;
char.mc.y = newY;
// set animation state
if (char.inAir)
newAnimState = "jump";
char.animstate = newAnimState;
// move along walk cycle
if (char.animstate == "walk")
char.animstep += timeDiff / 60;
if (char.animstep > char.walkAnimation.length)
char.animstep = 0;
char.mc.gotoAndStop(char.walkAnimation[Math.floor(char.animstep)]);
// not walking, show stand or jump state
else
char.mc.gotoAndStop(char.animstate);
// changed directions
if (newDirection != char.direction)
char.direction = newDirection;
char.mc.scaleX = char.direction;
public function checkCollisions()
for (var i = otherObjects.length-1; i >= 0; i--)
if (hero.mc.hitTestObject(otherObjects[i]))
getObject(i);
for (var j:int = enemies.length-1; j>=0; j--)
if (hero.mc.hitTestObject(enemies[j].mc))
currentX = hero.mc.x;
gameComplete();
public function scrollWithHero()
var stagePosition:Number = gamelevel.x + hero.mc.x;
var rightEdge:Number = stage.stageWidth - edgeDistance;
var leftEdge:Number = edgeDistance;
if (stagePosition > rightEdge)
gamelevel.x -= (stagePosition-rightEdge);
if (gamelevel.x < -(gamelevel.width-stage.stageWidth))
gamelevel.x = -(gamelevel.width-stage.stageWidth);
if (stagePosition < leftEdge)
gamelevel.x += (leftEdge-stagePosition);
if (gamelevel.x > 0)
gamelevel.x = 0;
public function getObject(objectNum:int)
if (otherObjects[objectNum] is Treasure)
gamelevel.removeChild(otherObjects[objectNum]);
otherObjects.splice(objectNum,1);
public function death()
if (hero.mc.y > 300)
currentX = gamelevel.hero.x;
trace(currentX);
gameComplete();
public function gameComplete()
gameMode = "dead";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Gameover";
public function clickDialogButton(event:MouseEvent)
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead")
// reset hero
hero.mc.x = currentX;
hero.mc.y = 0;
trace("dead");
setReplay();
gameMode = "play";
// give stage back the keyboard focus
stage.focus = stage;
public function setReplay()
for (var i:int = fixedObjects.length-1; i>-1; i--)
if (fixedObjects[i].leftside < currentX)
this.gamelevel.removeChildAt(fixedObjects[i]);
fixedObjects.splice(i,1);
trace("Splice?");
for each (var floorObject in fixedObjects){
trace(floorObject.leftside);
public function cleanUp()
removeChild(gamelevel);
this.removeEventListener(Event.ENTER_FRAME,gameLoop);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);Ok, I fiured it all out, the other way you mentioned. Just opened up the character MC, and named 2 frames. One LEFT and one RIGHT. Then I added a few simple lines of code, and turned out with this:
if (Key.isDown(Key.RIGHT)) {
_x += speed;
this.gotoAndStop("right");
if (Key.isDown(Key.LEFT)) {
_x -= speed;
this.gotoAndStop("left");
Thanks for helping!!!
Maybe you are looking for
-
Delete songs from iTunes library from "recently added" playlist
can you please add a function that removes songs from both the entire library and the recently added playlist by simply right clicking a song while in the "Recently Added" playlist that has the "Delete" function. this is very simple and would make iT
-
Sata Errors on start-up.
Hello, when I boot my laptop it gives me a repeating error after the Grub screen. [164266.343653] ata1.00: exception Emask 0x0 SAct 0xf SErr 0x0 action 0x6 frozen [164266.343662] ata1.00: failed command: WRITE FPDMA QUEUED [164266.343671] ata1.00: cm
-
Having trouble setting up file sharing through Airport Extreme
Hi, I am trying to set up file sharing on my USB hard drive through the Airport Extreme, on my HP laptop with Windows XP. I went through the steps in manual setup in Airport Utilities, and my hard drive shows up under the Disk Utility in the Airport
-
Hi all, I have the following xml file (books1.xml): <bookstore> <book> <BookID>1</BookID> <title>Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book> <BookID>2<BookID> <title>Harry Potter
-
When I first start Firefox I get a message that a particular font is not installed and asking me to allow it, not allow it, or show it in finder. It is a font that is in my font folder in my hard drive and is even listed on the font choices in the Pr