AS3 No keyboard input registering - actionscript-3

so I want an object to orbit around another, but I want it to do it only when the right arrow key is pressed. When I run this program, the orbiter doesn't move at all, even when the right arrow key is pressed and it doesn't trace!
Any help is greatly appreciated!
PS Do I have to use an event listener with KEY_DOWN or can I return a number and check it?
var orbiter:Orbiter = new Orbiter();
var origin:Origin = new Origin();
var angle:Number = 0;
var speed:Number = 1.5;
var radius:Number = 75;
origin.x= 100;
origin.y =100;
addChild(orbiter);
addChild(origin);
stage.addEventListener(Event.ENTER_FRAME, Orbit_Brah);
function Orbit_Brah(event:Event):void
{
var nLeftOrRight = CheckKeyDown;
if (nLeftOrRight == 1)
{
angle += speed;
var rad:Number = angle * (Math.PI / 180);
orbiter.x = origin.x + radius * Math.cos(rad);
orbiter.y = origin.y + radius * Math.sin(rad);
orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
}
}
function CheckKeyDown(event:KeyboardEvent):int
{
if (event.keyCode == Keyboard.RIGHT)
{
trace ("Key Press Registered");
return 1;
}
return 0;
}

You will need to add a listener to fetch the info from the KeyboardEvents. Store the info in a variable and use it in your update loop. You may also want to use KeyboardEvent.KEY_UP to check when the keys are released as well. Something like this.
stage.addEventListener(Event.ENTER_FRAME, Update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnKeyboardDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, OnKeyboardUpHandler);
function Update(pEvent : Event) : void
{
// update code here using stored info
if(_isMovingRight)
{
//
}
}
function OnKeyboardDownHandler(pEvent : KeyboardEvent) : void
{
switch(pEvent.keyCode)
{
case Keyboard.RIGHT:
_isMovingRight = true;
break;
}
}
function OnKeyboardUpHandler(pEvent : KeyboardEvent) : void
{
switch(pEvent.keyCode)
{
case Keyboard.RIGHT:
_isMovingRight = false;
break;
}
}

You're trying too hard. All you need to do after your declarations is:
stage.addEventListener(KeyboardEvent.KEY_DOWN, Orbit_Brah);
function Orbit_Brah(e)
{
if (e.keyCode == Keyboard.RIGHT)
{
angle += speed;
var rad:Number = angle * (Math.PI / 180);
orbiter.x = origin.x + radius * Math.cos(rad);
orbiter.y = origin.y + radius * Math.sin(rad);
orbiter.rotation = (Math.atan2(orbiter.y-origin.y, orbiter.x-origin.x) * 180 / Math.PI);
}
}
That still leaves you with one little math problem, which will be obvious when you run the code, but you can take care of that.

Related

Actionscript 3.0 Mouse trail snake game logic

I am developing a game in actionscript 3.0 (adobe flash) similar to this https://www.tvokids.com/preschool/games/caterpillar-count. I have the code for dragging the head of the snake in the direction of the mouse. However, I do not know how do I add the body of the snake and make it follow the path of the head. Following is my code to drag movieclip in the direction of the mouse :
var _isActive = true;
var _moveSpeedMax:Number = 1000;
var _rotateSpeedMax:Number = 15;
var _decay:Number = .98;
var _destinationX:int = 150;
var _destinationY:int = 150;
var _dx:Number = 0;
var _dy:Number = 0;
var _vx:Number = 0;
var _vy:Number = 0;
var _trueRotation:Number = 0;
var _player;
var i;
createPlayer();
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
function createPlayer():void{
_player = new head();
_player.x = stage.stageWidth / 2;
_player.y = stage.stageHeight / 2;
stage.addChild(_player);
}
function onDown(e:MouseEvent):void{
_isActive = true;
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
function onMove(e:MouseEvent):void{
updatePosition(_player);
updateRotation(_player);
}
function onUp(e:MouseEvent):void{
_isActive = false;
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp);
}
function updatePosition(mc):void
{
// check if mouse is down
if (_isActive)
{
// update destination
_destinationX = stage.mouseX;
_destinationY = stage.mouseY;
// update velocity
_vx += (_destinationX - mc.x) / _moveSpeedMax;
_vy += (_destinationY - mc.y) / _moveSpeedMax;
}
else
{
// when mouse is not down, update velocity half of normal speed
_vx += (_destinationX - mc.x) / _moveSpeedMax * .25;
_vy += (_destinationY - mc.y) / _moveSpeedMax * .25;
}
// apply decay (drag)
_vx *= _decay;
_vy *= _decay;
// if close to target, slow down turn speed
if (getDistance(_dx, _dy) < 50)
{
_trueRotation *= .5;
}
// update position
mc.x += _vx;
mc.y += _vy;
}
function updateRotation(mc):void
{
// calculate rotation
_dx = mc.x - _destinationX;
_dy = mc.y - _destinationY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx, _dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > mc.rotation + 180) rotateTo -= 360;
if (rotateTo < mc.rotation - 180) rotateTo += 360;
// ease rotation
_trueRotation = (rotateTo - mc.rotation) / _rotateSpeedMax;
// update rotation
mc.rotation += _trueRotation;
}
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y, delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
The script below will not miraculously work on its own, however it has all the logic you need, well-explained. It makes a chain of any length follow its head by certain rules. I used the same principle here many years ago: http://delimiter.ru/games/25-lines/alone.html
// This one will represent the Mouse position.
var Rat:Sprite = new Sprite;
// The ordered list of chain elements.
// It all starts with the Mouse.
var Snake:Array = [Rat];
// Call this one each time you want to
// extend the snake with the piece of tail.
function addTail(aPiece:DisplayObject):void
{
// Get the last snake element.
var lastPiece:DisplayObject = Snake[Snake.length - 1];
// Sync the tail coordinates.
aPiece.x = lastPiece.x;
aPiece.y = lastPiece.y;
// Add the new piece to the snake.
Snake.push(aPiece);
}
// Add the pre-defined head as the first element.
addTail(SnakeHead);
// Now start following the Mouse.
addEventListener(Event.ENTER_FRAME, onFrame);
// Fires every frame and adjusts the whole snake, if needed.
function onFrame(e:Event):void
{
// Sync the attractor point with the Mouse.
Rat.x = mouseX;
Rat.y = mouseY;
// Now lets make each piece follow the previous piece,
// one by one, starting from the head, down to the tail.
for (var i:int = 1; i < Snake.length; i++)
{
followOne(Snake[i - 1], Snake[i]);
}
}
function followOne(A:DisplayObject, B:DisplayObject):void
{
// Think of these values as of vector
// pointing from B position to A position.
var dx:Number = A.x - B.x;
var dy:Number = A.y - B.y;
// Figure out the distance between the given pieces.
var aDist:Number = Math.sqrt(dx * dx + dy * dy);
// Do nothing if pieces are closer than 20 px apart.
// You can change this value to make snake shorter or longer.
if (aDist < 20)
{
return;
}
// This literally means "eat one tenth of the distance
// between me and the previous piece". If you want pieces
// to follow each other with more vigor, reduce this value,
// if you want the whole snake to slither smoothly, increase it.
B.x += dx / 10;
B.y += dy / 10;
// Rotate the B piece so it would look right into A's direction.
// Well, unless your pieces are round and look all the same.
B.rotation = Math.atan2(dy, dx) * 180 / Math.PI;
}

Adding another Movie Clip into another Frame

I am attempting to add a new movie clip into the next frame of my shooter game.
I am using Actionscript 3.0
To give a basis of what I need help with for my assessment. When the score =50, switch to the next frame. And this is where I would like to add a new type of movie clip for the user to shoot!
Here is the code I have so far.
FRAME 1
//Tate's open screen
stop(); //makes the screen wait for events
paraBtn.addEventListener(MouseEvent.CLICK, playClicked); //this line is making your button an mouse click event
function playClicked(evt: MouseEvent): void { // now we are calling the event from this function and telling it to go to the next frame we labelled play
gotoAndStop("frame2");
// All rights of this music goes towards the makers of the game "Risk of Rain" which was made by Hapoo Games
}
FRAME 2 (Where the game actually starts)
stop();
// This plays the sound when left click is used
var spitSound: Sound = new Sound();
spitSound.load(new URLRequest("gunSound.mp3"));
//This plays the gameover sound when your lives reach 0
var overSound: Sound = new Sound();
overSound.load(new URLRequest("Gameover.mp3"));
//This plays the sound when you are hit
var etSound: Sound = new Sound();
etSound.load(new URLRequest("Urgh.mp3"));
//This sets the lives and points.
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimTurret);
var points: Number = 0;
var lives: Number = 3;
var target: MovieClip;
var _health: uint = 100;
initialiseCursor();
//This variable stops the multiple errors with the move objects and bullets and range to stop compiling.
var Gameover: Boolean = false;
//This aims the turrent to where you mouse is on the screen
function aimTurret(evt: Event): void {
if (Gameover == false) {
gun.rotation = getAngle(gun.x, gun.y, mouseX, mouseY);
var distance: Number = getDistance(gun.x, gun.y, mouseX, mouseY);
var adjDistance: Number = distance / 12 - 7;
}
}
function getAngle(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var radians: Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}
function getDistance(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var dx: Number = x2 - x1;
var dy: Number = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
function rad2deg(rad: Number): Number {
return rad * (180 / Math.PI);
}
//Starts lives and shows text next to the numbers
function initialiseCursor(): void {
Mouse.hide();
target = new Target();
target.x = mouseX;
target.y = mouseY;
target.mouseEnabled = false;
addChild(target);
stage.addEventListener(MouseEvent.MOUSE_MOVE, targetMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, targetDown);
stage.addEventListener(MouseEvent.MOUSE_UP, targetUp);
livesdisplay.text = String(lives) + " Lives Left";
pointsdisplay.text = String(points) + " Points";
}
function targetMove(evt: MouseEvent): void {
target.x = this.mouseX;
target.y = this.mouseY;
}
function targetDown(evt: MouseEvent): void {
target.gotoAndStop(2);
}
function targetUp(evt: MouseEvent): void {
target.gotoAndStop(1);
}
//Starts bullets and speed of bullets, also addding new arrays for baddies
var gunLength: uint = 90;
var bullets: Array = new Array();
var bulletSpeed: uint = 20;
var baddies: Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
function fireGun(evt: MouseEvent) {
if (Gameover == false) {
var bullet: Bullet = new Bullet();
bullet.rotation = gun.rotation;
bullet.x = gun.x + Math.cos(deg2rad(gun.rotation)) * gunLength;
bullet.y = gun.y + Math.sin(deg2rad(gun.rotation)) * gunLength;
addChild(bullet);
bullets.push(bullet);
spitSound.play();
}
}
function deg2rad(deg: Number): Number {
return deg * (Math.PI / 180);
}
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function moveObjects(evt: Event): void {
if (Gameover == false) {
moveBullets();
moveBaddies();
}
}
function moveBullets(): void {
for (var i: int = 0; i < bullets.length; i++) {
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x < -bullets[i].width || bullets[i].x > stage.stageWidth + bullets[i].width || bullets[i].y < -bullets[i].width || bullets[i].y > stage.stageHeight + bullets[i].width) {
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
// This is the start of the timer
var timer: Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
// Adding army men on a timer and only from the top side
function addBaddie(evt: TimerEvent): void {
var baddie: Baddie = new Baddie();
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = -baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}
function moveBaddies(): void {
for (var i: int = 0; i < baddies.length; i++) {
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(gun.x, gun.y, true)) {
removeChild(baddies[i]);
baddies.splice(i, 1);
loseLife();
//If baddie was removed then we don’t check for bullet hits
} else {
checkForHit(baddies[i]);
}
}
}
function checkForHit(baddie: Baddie): void {
for (var i: int = 0; i < bullets.length; i++) {
if (baddie.hitTestPoint(bullets[i].x, bullets[i].y, true)) {
removeChild(baddie);
points++;
if (points == 50) {
gotoAndStop("frame3")
}
pointsdisplay.text = String(points) + " Points";
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
// Keeping track of lost lives and when hitting 0 doing to frame four, also displaying "Lose life!"
function loseLife(): void {
etSound.play();
lives--;
if (lives == 0) {
Gameover = true;
overSound.play();
gotoAndStop("frame4")
}
livesdisplay.text = String(lives) + " Lives Left";
trace("Lose Life!");
}
FRAME 3 (This is where I need help, to add another movie clip) (I have made one for the frame named, "BaddieRed" With the Linkage being "Baddiered"
stop();
// The code from frame2 carries over and works the same in this frame
FRAME 4 (This is the screen where it's gameover)
stop();
timer.stop();
// User need to close by pressing the close button
//And restart the game manually
Is this what you're trying to achieve? Something like...
function addBaddie(evt: TimerEvent): void
{
var baddie : MovieClip;
if (points < 50) { var bad1: Baddie = new Baddie(); baddie = bad1; }
if (points >= 50) { var bad2 : Baddiered = new Baddiered(); baddie = bad2; }
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y -= baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}

How do i detect collision and stack falling objects in as3 flash?

I have a little problem when I'm trying to get the sqares to stack, almost like in tetris.
I don't know how I can controll the different squares so i can check for collision. I have made one square with as3 linkage name Square.
var timer:Timer = new Timer(12);
timer.addEventListener(TimerEvent.TIMER, doStuff);
timer.start();
var newSquare= new Square();
nyFirkant.y = 0;
nyFirkant.x = Math.floor( Math.random() * 4) * 100;
addChild(newSquare);
stage.addEventListener(KeyboardEvent.KEY_DOWN, tastLytter);
function keyListener(evt:KeyboardEvent)
{
var key:int = evt.keyCode;
if (key== Keyboard.RIGHT && newSquare.x < 400)
{
newSquare.x += 100;
}
if (key== Keyboard.LEFT && newSquare.x > 0)
{
newSquare.x -= 100;
}
}
function doStuff(evt:TimerEvent)
{
if (newSquare.y <= 400 - newSquare.height)
{
newSquare.y = newSquare.y + 2;
}
if (newSquare.y == 350)
{
newSquare= new Square();
newSquare.y = 0;
newSquare.x = Math.floor( Math.random() * 4) * 100;;
addChild(newSquare);
}
}
Use hitTestObject, it's a method in the MovieClip class.
if (firstBlock.hitTestObject(secondBlock)) {
trace("This block hit the other block");
//Do stuff
}
Obviously this isn't a "drop-in" solution - you'd be much better off using a physics engine such as Box2D, but hitTestObject should do fine for your purposes.

Accessing timeline variables from a class?

In one of the frame of my program I have code for a "player" that is essentially a cannon that follows the character around, specifics aren't important. So I'd like to make this cannon into a class that I can then place as a movieclip, on the stage and have similar cannons serving similar functions. So Basicly I need to make this into a class that somehow interacts with timeline variables?
right now the Player class looks like this
package
{
import flash.display.*;
import flash.events.*;
import flash.ui.*;
public class Player extends MovieClip
{
public function Player() {
}
}
}
Warning code dump you don't have to read all this, this is the player code that I need to make into a class so that I can make more players with different parameters to their not all following the character etc... So how do I do this? this code is interacting with objects on the stage and other variables in the timeline at the moment.
// player settings
var _rotateSpeedMax:Number = 20;
var _gravity:Number = .10;
// projectile gun settings
var _bulletSpeed:Number = 4;
var _maxDistance:Number = 200;
var _reloadSpeed:Number = 250;//milliseconds
var _barrelLength:Number = 20;
var _bulletSpread:Number = 5;
// gun stuff
var _isLoaded:Boolean = true;
var _isFiring:Boolean = false;
var _endX:Number;
var _endY:Number;
var _startX:Number;
var _startY:Number;
var _reloadTimer:Timer;
var _bullets:Array = [];
// array that holds walls
var _solidObjects:Array = [];
// global vars
var _player:MovieClip;
var _dx:Number;
var _dy:Number;
var _pcos:Number;
var _psin:Number;
var _trueRotation:Number;
/**
* Constructor
*/
_solidObjects = [world.wall01,world.wall02,world.wall03,world.wall04];
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
//character.addEventListener(Event.ENTER_FRAME, moveDude);
//////////////////////////////////////;
// Player & Weapon Methods
//////////////////////////////////////
/**
* Creates player
* Uses "Player" movieclip linked in library
*/
createPlayer();
function createPlayer():void
{
// attach player movieclip from library
// position player in center
if (character!=null&&_player!=null)
{
_player.x = character.x +5;
_player.y = character.y +5;
}
else if (_player ==null)
{
_player = new Player();
// add to display list
stage.addChild(_player);
}
}
/**
* Fire weapon
*/
function fire():void
{
// check if firing
if (! _isFiring)
{
return;
}
// check if reloaded
if (! _isLoaded)
{
return;
}
// create bullet
createBullet();
// start reload timer
_reloadTimer = new Timer(_reloadSpeed);
_reloadTimer.addEventListener(TimerEvent.TIMER, reloadTimerHandler);
_reloadTimer.start();
// set reload flag to false;
_isLoaded = false;
}
/**
* Creates a bullet movieclip and sets it's properties
*/
function createBullet():void
{
// precalculate the cos & sine
_pcos = Math.cos(_player.rotation * Math.PI / 180);
_psin = Math.sin(_player.rotation * Math.PI / 180);
// start X & Y
// calculate the tip of the barrel
_startX = _player.x - _barrelLength * _pcos;
_startY = _player.y - _barrelLength * _psin;
// end X & Y
// calculate where the bullet needs to go
// aim 50 pixels in front of the gun
_endX = _player.x - 50 * _pcos + Math.random() * _bulletSpread - _bulletSpread * .5;
_endY = _player.y - 50 * _psin + Math.random() * _bulletSpread - _bulletSpread * .5;
// attach bullet from library
var tempBullet:MovieClip = new Bullet();
// calculate velocity
tempBullet.vx = (_endX - _startX) / _bulletSpeed;
tempBullet.vy = (_endY - _startY) / _bulletSpeed;
// set position
tempBullet.x = _startX;
tempBullet.y = _startY;
// save starting location
tempBullet.startX = _startX;
tempBullet.startY = _startY;
// set maximum allowed travel distance
tempBullet.maxDistance = stage.stageHeight;//_maxDistance;
// add bullet to bullets array
_bullets.push(tempBullet);
// add to display list;
stage.addChild(tempBullet);
}
/**
* Updates bullets
*/
function updateBullets():void
{
var i:int;
var tempBullet:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullet = _bullets[i];
// check if gravity is enabled
if (gravityCheckbox.selected)
{
// add gravity to Y velocity
tempBullet.vy += _gravity;
}
// update bullet position
tempBullet.x += tempBullet.vx;
tempBullet.y += tempBullet.vy;
// check if bullet went too far
if (getDistance(tempBullet.startX - tempBullet.x, tempBullet.startY - tempBullet.y) > tempBullet.maxDistance + _barrelLength)
{
destroyBullet(tempBullet);
}
// check for collision with walls
if (checkCollisions(tempBullet.x,tempBullet.y))
{
destroyBullet(tempBullet);
}
}
}
/**
* Destroys bullet
* #parambulletTakes bullet movieclip
*/
function destroyBullet(bullet:MovieClip):void
{
var i:int;
var tempBullet:MovieClip;
// loop thru _bullets array
for (i = 0; i < _bullets.length; i++)
{
// save a reference to current bullet
tempBullet = _bullets[i];
// if found bullet in array
if (tempBullet == bullet)
{
// remove from array
_bullets.splice(i, 1);
// remove from display list;
bullet.parent.removeChild(bullet);
// stop loop;
return;
}
}
}
/**
* Reload weapon
*/
function reloadWeapon():void
{
_isLoaded = true;
}
/**
* Checks for collisions between points and objects in _solidObjects
* #returnCollision boolean
*/
function checkCollisions(testX:Number, testY:Number):Boolean
{
var i:int;
var tempWall:MovieClip;
// loop thru _solidObjects array
for (i = 0; i < _solidObjects.length; i++)
{
// save a reference to current object
tempWall = _solidObjects[i];
// do a hit test
if (tempWall.hitTestPoint(testX,testY,true))
{
return true;
// stop loop
break;
}
}
return false;
}
/**
* Calculate player rotation
*/
function updateRotation():void
{
// calculate rotation based on mouse X & Y
_dx = _player.x - stage.mouseX;
_dy = _player.y - stage.mouseY;
// which way to rotate
var rotateTo:Number = getDegrees(getRadians(_dx,_dy));
// keep rotation positive, between 0 and 360 degrees
if (rotateTo > _player.rotation + 180)
{
rotateTo -= 360;
}
if (rotateTo < _player.rotation - 180)
{
rotateTo += 360;
}
// ease rotation
_trueRotation = (rotateTo - _player.rotation) / _rotateSpeedMax;
// update rotation
_player.rotation += _trueRotation;
}
//////////////////////////////////////
// Event Handlers
//////////////////////////////////////
/**
* Enter Frame handler
* #parameventUses Event
*/
function enterFrameHandler(event:Event):void
{
createPlayer();
updateRotation();
updateBullets();
fire();
}
/**
* Mouse Up handler
* #parameUses MouseEvent
*/
function onMouseUpHandler(event:MouseEvent):void
{
_isFiring = false;
}
/**
* Mouse Down handler
* #parameUses MouseEvent
*/
function onMouseDownHandler(event:MouseEvent):void
{
_isFiring = true;
}
/**
* Reload timer
* #parameTakes TimerEvent
*/
function reloadTimerHandler(e:TimerEvent):void
{
// stop timer
e.target.stop();
// clear timer var;
_reloadTimer = null;
reloadWeapon();
}
//////////////////////////////////////
// Utilities
//////////////////////////////////////
/**
* Get distance
* #paramdelta_x
* #paramdelta_y
* #return
*/
function getDistance(delta_x:Number, delta_y:Number):Number
{
return Math.sqrt((delta_x*delta_x)+(delta_y*delta_y));
}
/**
* Get radians
* #paramdelta_x
* #paramdelta_y
* #return
*/
function getRadians(delta_x:Number, delta_y:Number):Number
{
var r:Number = Math.atan2(delta_y,delta_x);
if (delta_y < 0)
{
r += (2 * Math.PI);
}
return r;
}
/**
* Get degrees
* #paramradiansTakes radians
* #returnReturns degrees
*/
function getDegrees(radians:Number):Number
{
return Math.floor(radians/(Math.PI/180));
}
From the class you can access a variable like this: MovieClip(root).variable

How do I get velocity for my character in as3

im trying to make a teleporter game and my character needs to have some velocity and gravity, does anyone know what sums i need to be able to acomplish this?
This is my code so far:
var char = this.addChild(new Char());
char.width = 20;
char.height = 20;
char.x = startPos.x; //startPos is an invisible movieclip that I can move around to make the starting position
char.y = startPos.y; // accurate
var vx:Number = 0;
var vt:Number = 0;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyDownHandler (e:KeyboardEvent):void {
switch (e.keyCode) {
case Keyboard.UP:
char.y = char.y - 5
}
}
If your char only needs to go up then the following code will do the job.
But if it needs to move in all direction then much advanced code is required.
Follow Moving Character in all directions.
This is a quick solution to your need.
var gravity:Number = 2;
var velocity:Number = 1.1;
var move:Boolean = false;
function moveChar(e:Event):void
{
if(move)
{
gravity *= velocity;
char.y -= gravity; // move char
}
}
char.addEventListener(Event.ENTER_FRAME, moveChar, false, 0, true);
//Keyboard events
function keyDownHandler (e:KeyboardEvent):void
{
switch (e.keyCode)
{
case Keyboard.UP:
move = true;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
function keyUpHandler (e:KeyboardEvent):void
{
move = false;
gravity = 2;
}
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);