ActionScript 3 code for a 2D driving car

posted by Nick - 17:35 22/01/10

Hello,

I’m going to post some ActionScript 3 code for a 2D driving car. I wrote the code for our Christmas viral campaign – 'Santa's Christmas Crackered!' – check it out: http://www.d2digital.co.uk/viral.aspx. Its purpose is to raise drink driving awareness throughout the Christmas period in an engaging way.

Well, in this case it was the car was a sleigh and there was quite a bit of other code which caused the sleigh to wobble when Santa gets sloshed, but I’m not going include those bits of extraneous code here.

I felt I ought to post this as it is adapted from an article that I found online describing an AS2 version [http://www.actionscript.org/resources/articles/648/1/Car-Movement/Page1.html].

Here's the code for our version;


package  
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	
	public class Car extends MovieClip 
	{
		public const FRICTIONMOD:Number = 0.97; // 1 = no friction
				
		// ACCELERATING
		public const MAXSPEED:Number = 10;
		public const ACCELERTAION:Number = 0.25;
		
		// REVERSING
		public const REVERSEMAXSPEED:Number = -2;
		public const REVERSEACCELERTAION:Number = 0.2;
		
		// TURNING SPEEDS
		public const MAXTURNRATE:Number = 5;
		public const TURNIMPACTONSPEED = 0.99; // less is more
		
		// KEY BOOLS
		public var speed:Number = new Number(0);
		public var pressedKeys:Object = {}; 
		private var pressUp:Boolean = false;
		private var pressDown:Boolean = false;
		private var pressLeft:Boolean = false;
		private var pressRight:Boolean = false;
		private var pressSpace:Boolean = false;
		private var pressCtrl:Boolean = false;
		
		// Initialization:
		public function Car() 
		{
			stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			this.addEventListener(Event.ENTER_FRAME, ModifyCar);
		}
		
		public function ModifyCar(eFrame:Event)
		{
			if (pressUp && !pressCtrl) 
				speed += ACCELERTAION;
			
			// slow down based on friction modifier
			speed = speed * FRICTIONMOD;
			
			// reversing
			if (pressDown) 
				speed -= REVERSEACCELERTAION;
			
			// turning right
			if (pressRight) 
			{   
				// turn amount based on speed
				if (speed > MAXSPEED/4)
					this.rotation += MAXTURNRATE;
			
				else if (speed < (MAXSPEED/4) && speed >= 0)     
					this.rotation += ((MAXTURNRATE/4) * speed);
							
				else if (speed < 0) 
					this.rotation += (MAXTURNRATE * speed / ((MAXSPEED/4)*3));
				
				speed *= TURNIMPACTONSPEED;
			}
			
			// turning left
			if (pressLeft) 
			{   
				if (speed > MAXSPEED/4)    
					this.rotation -= MAXTURNRATE;    
			
				else if (speed < (MAXSPEED/4) && speed >= 0)    
					this.rotation -= (MAXTURNRATE/4) * speed;    
							
				else if (speed < 0)   
					this.rotation -= MAXTURNRATE * speed / ((MAXSPEED/4)*3);
				
				speed *= TURNIMPACTONSPEED;
			}
			
			// some very clever maths
			this.x += Math.sin (this.rotation * Math.PI / 180) * speed;
			this.y += Math.cos (this.rotation * Math.PI / 180) * -speed;
			
			// cap the speed to max speed
			if (Math.abs (speed) > MAXSPEED) 
				speed = MAXSPEED;
			
			if (speed < REVERSEMAXSPEED)   
				speed = REVERSEMAXSPEED;
		
			// handrake
			if (pressCtrl) 
			{    
				speed -= speed / (MAXSPEED/2);
				
				// skid
				if (pressRight)     
					this.rotation += speed / 2;
				if (pressLeft)        
					this.rotation -= speed / 2;    
			}
		}
		
		private function keyDownHandler(e:KeyboardEvent):void
		{
			modifyKeyStatus(e, true);
		}
		private function keyUpHandler(e:KeyboardEvent):void
		{
			modifyKeyStatus(e, false);
		}
		
		private function modifyKeyStatus(e:KeyboardEvent, keyActive:Boolean):void
		{			
			switch(e.keyCode)
			{
				case 38 :
					pressUp = keyActive;
					break;
				case 40 :
					pressDown = keyActive;
					break;
				case 39 :
					pressRight = keyActive;
					break;
				case 37 :
					pressLeft = keyActive;
					break;
				case 32 :
					pressSpace = keyActive;
					break;
				case 17 :
					pressCtrl = keyActive;
					break;
			}
		}
		
		public function KillControl():void
		{
			this.removeEventListener(Event.ENTER_FRAME, ModifyCar);
			
			stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			
			pressDown = false;
			pressUp = false;
			pressRight = false;
			pressLeft = false;
			pressSpace = false;
			pressCtrl = false;
		}
	}
}

Here’s the end result (I added an exhaust not in the posted code);
Click on the movie before using keyboard controls.

Create a movie-clip, link it to this class, drag it onto the stage and you're off! I made some constants in the class so that the behaviour of the car should be easier to change.

Our viral game also used pixel perfect collision detection and an inverted track shape to test for collisions with the side of the road.

Jolly good then,

Nick

There are no comments yet - why not be the first to leave one?

Leave a comment

CAPTCHA code image
Speak the codeChange the code