ActionScript 3 Car Movement with fuel






In today’s post I will show the code for the movement of a car in actionscript 3. It has a fuel counter that can refuel.

car movement actionscript 3

See live example clicking here

You can download all the files clicking here

Movement.as

package {

import HitTest;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.utils.*;
public class carMovement extends MovieClip{

var combustible:Number=200;

var a:Number = 4;
var vx:Number = 0;
var vy:Number = 0;
var dir:Number = 0;
var friccion:Number = 0.9;
var piover180:Number = Math.PI /180;

var key_left:Boolean = false;
var key_right:Boolean = false;
var key_up:Boolean = false;
var key_down:Boolean = false;
public function carMovement() {
stage.addEventListener(KeyboardEvent.KEY_DOWN, teclaPresionada);
stage.addEventListener(KeyboardEvent.KEY_UP,teclaLevantada);

addEventListener(Event.ENTER_FRAME,Main);
}
function Main(event:Event){
CheckKeys();
moveCar();
refuel();
fuel();
}

function fuel(){
if(combustible==0){
gasolina.text="No fuel";
}else{
combustible--;
gasolina.text=String(combustible);
}
}
function teclaPresionada(e:KeyboardEvent): void {
switch(e.keyCode)
{
case 38 :
key_up = true;
break;
case 40 :
key_down = true;
break;
case 39 :
key_right = true;
break;
case 37 :
key_left = true;
break;
}
}
function teclaLevantada(e:KeyboardEvent): void {
switch(e.keyCode)
{
case 38 :
key_up = false;
break;
case 40 :
key_down = false;
break;
case 39 :
key_right = false;
break;
case 37 :
key_left = false;
break;
}
}
function CheckKeys(){

if(combustible>0){

if(key_left){
coche.rotation -= 4*dir;
coche.delanteras.rotation = Math.min(24,Math.max(-24,coche.delanteras.rotation-5));
coche.delanteras.rotation = Math.min(24,Math.max(-24,coche.delanteras.rotation-5));

} else if(key_right){
coche.rotation += 4*dir;
coche.delanteras.rotation = Math.min(24,Math.max(-24,coche.delanteras.rotation+5));
coche.delanteras.rotation = Math.min(24,Math.max(-24,coche.delanteras.rotation+5));
} else {
coche.delanteras.rotation=0;
coche.delanteras.rotation=0;
}
if(key_up){

if(dir<=2.5){
dir += 0.05;
}

} else if(key_down){
dir = -0.5;

} else {

if(dir>0){
dir -= 0.05;
}else{
dir=0;
}

}
}else{
coche.delanteras.rotation=0;
coche.delanteras.rotation=0;

if(dir>0){
dir -= 0.05;
}else{
dir=0;
}

}
}

function moveCar(){

vx *= friccion;
vy *= friccion;
coche.x += Math.sin(coche.rotation*piover180)*a*dir;
coche.y -= Math.cos(coche.rotation*piover180)*a*dir;

}
function refuel(){

if(HitTest.complexHitTestObject(gasStation,coche)){

combustible+=2;
}

}

}

}




 
Leave a Comment
Your comment: