25Jan
[AS 3] Keyboard Events with Acceleration
No commentsHere is just a simple interactive animation. You can control the wheel with your left and right keys. When the object is off the screen, it will wrap around to the other side. You can view the project here in a new window, click the flash movie to activate.I created a new wheel class that imports in a .png file:
package {
import flash.display.Sprite;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.net.URLRequest;
import flash.events.Event;
import flash.events.ProgressEvent;
public class Wheel extends Sprite {
private var myImg:Loader = new Loader();
public var radius:Number;
public function Wheel(radius:Number = 100) {
this.radius = radius;
init();
}
public function init():void {
// let's load the image
try {
myImg.load(new URLRequest("wheel.png"));
}
catch (error:Error)
{
trace ("Unable to load requested document.");
}
myImg.contentLoaderInfo.addEventListener(Event.COMPLETE,result);
}
public function result(evt:Event):void
{
addChild(myImg);
myImg.width = myImg.height = radius * 2;
// change the registration point
myImg.x = -1 * radius;
myImg.y = -1 * radius;
}
}
}
Here is the document class to control all of this, named WheelToGround.as
package{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class WheelToGround extends Sprite {
private var wheel:Wheel;
private var vx:Number = 0;
private var accelerationRate:Number = 0
private var line:Sprite;
public function WheelToGround()
{
init();
}
private function init():void
{
// Create the Ground:
line = new Sprite();
line.graphics.lineStyle(1);
line.graphics.moveTo(0, stage.stageHeight - 10);
line.graphics.lineTo(stage.stageWidth, stage.stageHeight - 10);
addChild(line);
// Get the wheel
wheel = new Wheel(50);
addChild(wheel);
wheel.x = stage.stageWidth / 2;
wheel.y = stage.stageHeight - 10 - wheel.radius;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
private function onKeyDown(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.LEFT)
{
accelerationRate = -0.2;
}
else if(event.keyCode == Keyboard.RIGHT)
{
accelerationRate = 0.2;
}
}
private function onKeyUp(event:KeyboardEvent):void
{
accelerationRate = 0;
}
private function onEnterFrame(event:Event):void
{
vx += accelerationRate;
wheel.x += vx;
wheel.rotation += vx;
// is it off the screen?
if ( wheel.x > stage.stageWidth + wheel.width )
{
wheel.x = 0 - wheel.width;
}
else if ( wheel.x < 0 - wheel.width )
{
wheel.x = stage.stageWidth + wheel.width;
}
}
}
}
Categories: Actionscript 3, Physics
Friday, January 25th, 2008 at 3:19 pm and is filed under Actionscript 3, Physics. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.