Sam
Sam

Reputation: 500

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

Upvotes: 0

Views: 156

Answers (1)

Rajneesh Gaikwad
Rajneesh Gaikwad

Reputation: 1193

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);

Upvotes: 1

Related Questions