Controllable Flash Character

I have been working with flash and I have made a controllable character that you can make run and jump. I used this code. I think that it is daft that you have to put so much code just to control a character. but the results are worth it.

import flash.events.*;

hero.gotoAndStop(‘still’);

var Key:KeyObject = new KeyObject(stage);

var dy:Number=0;

var gravity:Number=1;

var canjump:Boolean = false;

stage.addEventListener(Event.ENTER_FRAME,onenter);

function onenter (e:Event) : void
{
//jumping and gravity

dy+=gravity;

if(hero.y>300){

dy=0;
canjump=true;

}

if(Key.isDown(Key.UP) && canjump) {

dy=-10;
canjump=false;
}
hero.y+=dy;

if(Key.isDown(Key.UP))
{hero.gotoAndStop(‘jump’);

}

//movement left and right stoping and staring
if(Key.isDown(Key.RIGHT))
{
hero.x+=5;
hero.scaleX=-1;
hero.gotoAndStop(‘walking’);
}

if(Key.isDown(Key.LEFT))
{
hero.x-=5;
hero.scaleX=1;
hero.gotoAndStop(‘walking’);
}
else
{
if(!Key.isDown(Key.RIGHT)&& !Key.isDown(Key.UP) && !Key.isDown(Key.LEFT))
{

hero.scaleX=-1;
hero.gotoAndStop(‘still’);
}
}
}

I also had a tie in document

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];
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s