Skip to content

Instantly share code, notes, and snippets.

@icio
Created February 18, 2011 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icio/834328 to your computer and use it in GitHub Desktop.
Save icio/834328 to your computer and use it in GitHub Desktop.
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
public var player:Sprite = new Sprite();
// Velocity
public var vx:Number = 0;
public var vy:Number = 0;
public var j:Number = 15; // Jump speed
// Acceleration
public var ax:Number = 0;
public var ay:Number = 0;
public var g:Number = 2; // Gravitational acceleration
// Keys pressed (left/right arrow)
public var kx:uint = 0;
public function Main()
{
drawPlayer();
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
public function onEnterFrame(event:Event):void
{
// Accelerate the player
vx += ax;
vy += ay;
ay = 0; // If we jumped, we're done
vx *= 0.5; // Friction
vy += g; // Gravity
// Move the player
player.x += vx;
player.y += vy;
// Keep the player in bounds
if (player.x < 0) {
player.x = 0;
vx *= -0.8;
} else if (player.x + player.width > stage.stageWidth) {
player.x = stage.stageWidth - player.width;
vx *= -0.8;
}
// Keep the player above the ground
if (player.y + player.height > stage.stageHeight) {
player.y = stage.stageHeight - player.height;
vy = 0;
}
}
public function onKeyDown(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.LEFT) {
kx = Keyboard.LEFT;
ax = -10;
} else if (event.keyCode == Keyboard.RIGHT) {
kx = Keyboard.RIGHT;
ax = 10;
}
if (event.keyCode == Keyboard.UP) {
ay = -j;
}
}
public function onKeyUp(event:KeyboardEvent):void
{
if (kx && event.keyCode == kx) {
kx = 0;
ax = 0;
}
}
public function drawPlayer():void
{
player.graphics.beginFill(0xFF, 0.5);
player.graphics.drawRect(0, 0, 20, 20);
player.graphics.endFill();
player.x = stage.stageWidth / 2;
player.y = stage.stageHeight / 2;
addChild(player);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment