Hello again, Today i will following up on my previous tutorial LINK and will be teaching you how to add forward movement to your movieclip and left right controls (kinda like Asteroids).
If you don’t have the original source you can download it HERE.
First we declare and define some lovely variables. These will be our starting velocity values, one for the X axis and one for the Y axis.
xVel = 2; yVel = 2;
woo look at those variables… tasty. These two vaiables will set our initial movement at runtime.
But how do we use these to add movement?! We’ll need an event listener attached to our movieclip!
Beans_MC.addEventListener(Event.ENTER_FRAME, update);
function update(Event)
{
//update code in here
}
This will run the update function every time our Beans_MC enters the next frame.
next the code to actually do something!
Beans_MC.addEventListener(Event.ENTER_FRAME, update);
function update(Event)
{
Beans_MC.x += xVel;
Beans_MC.y += yVel;
}
Ooh lovely code! This will add our velocity values on to the X & Y coordinates of our Beans_MC, updating its position on the stage.
If you test this now you see that it moves allong just fine. But wait a minute. why does it keep going!?
For this we need to add drag!
first add a new variable underneath our velocity pair….
var drag:Number = 0.98;
Mysterious…
Now change the update function as shown here.
Beans_MC.addEventListener(Event.ENTER_FRAME, update);
function update(Event)
{
Beans_MC.x += xVel;
Beans_MC.y += yVel;
xVel *= drag;
yVel *= drag;
}
Test that damn movie! OMG! its slowing down! like it has friction or drag applied to it!
woo! congratulations you have now used velocity and drag in AS3.
Bye!
Also here are my source files…
[...] even more games (completed Dead Space finally!) to bring you a follow up to my previous tutorial BLAHLINK. This Tutorial will show you how to add forward momentum in the correct direction based on the [...]