Free ActionScript

Flash AS2 & AS3 Tutorials, Game Code, Effects, Source Files & Sample Downloads

Car Movement: Acceleration, Turning & Braking

12 Comments »

AS3 version of my previous GTA style top-down view car driving game example. This example shows you how to implement car movement; Acceleration, Braking & Turning.

View Code ACTIONSCRIPT
/**
 * Car Movement - Accelerate, Brake, Rotate & Reverse
 * ---------------------
 * VERSION: 2.0
 * DATE: 1/09/2011
 * AS3
 * UPDATES AND DOCUMENTATION AT: http://www.FreeActionScript.com
 **/
package com.freeactionscript
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
 
	public class Car extends Sprite
	{
		//Settings
		private var speed:Number = 0;
		private var speedMax:Number = 8;
		private var speedMaxReverse:Number = -3;
		private var speedAcceleration:Number = .15;
		private var speedDeceleration:Number = .90;
		private var groundFriction:Number = .95;
 
		private var steering:Number = 0;
		private var steeringMax:Number = 2;
		private var steeringAcceleration:Number = .10;
		private var steeringFriction:Number = .98;
 
		private var velocityX:Number = 0;
		private var velocityY:Number = 0;
 
		private var up:Boolean = false;
		private var down:Boolean = false;
		private var left:Boolean = false;
		private var right:Boolean = false;
 
		public function Car()
		{
			addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		}
 
		private function onAddedToStage(event:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
 
			init();
		}
 
		private function init():void
		{
			stage.addEventListener(Event.ENTER_FRAME, runGame);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, myOnPress);
			stage.addEventListener(KeyboardEvent.KEY_UP, myOnRelease);
		}
 
		private function runGame(event:Event):void
		{
			if (up)
			{
				//check if below speedMax
				if (speed < speedMax) 				{ 					//speed up 					speed += speedAcceleration; 					//check if above speedMax 					if (speed > speedMax)
					{
						//reset to speedMax
						speed = speedMax;
					}
				}
			}
 
			if (down)
			{
				//check if below speedMaxReverse
				if (speed > speedMaxReverse)
				{
					//speed up (in reverse)
					speed -= speedAcceleration;
					//check if above speedMaxReverse
					if (speed < speedMaxReverse) 					{ 						//reset to speedMaxReverse 						speed = speedMaxReverse; 					} 				} 			} 			 			if (left) 			{ 				//turn left 				steering -= steeringAcceleration; 				//check if above steeringMax 				if (steering > steeringMax)
				{
					//reset to steeringMax
					steering = steeringMax;
				}
			}
 
			if (right)
			{
				//turn right
				steering += steeringAcceleration;
				//check if above steeringMax
				if (steering < -steeringMax) 				{ 					//reset to steeringMax 					steering = -steeringMax; 				} 			} 			 			// friction     			speed *= groundFriction; 			 			// prevent drift 			if(speed > 0 && speed < 0.05) 			{ 				speed = 0 			} 			 			// calculate velocity based on speed 			velocityX = Math.sin (this.rotation * Math.PI / 180) * speed; 			velocityY = Math.cos (this.rotation * Math.PI / 180) * -speed; 			 			// update position	 			this.x += velocityX; 			this.y += velocityY; 			 			// prevent steering drift (right) 			if(steering > 0)
			{
				// check if steering value is really low, set to 0
				if(steering < 0.05)
				{
					steering = 0;
				}
			}
			// prevent steering drift (left)
			else if(steering < 0) 			{ 				// check if steering value is really low, set to 0 				if(steering > -0.05)
				{
					steering = 0;
				}
			}
 
			// apply steering friction
			steering = steering * steeringFriction;
 
			// make car go straight after driver stops turning
			steering -= (steering * 0.1);
 
			// rotate
			this.rotation += steering * speed;
		}
 
		/**
		 * Keyboard Handlers
		 */
		private function myOnPress(event:KeyboardEvent):void
		{
			switch( event.keyCode )
			{
				case Keyboard.UP:
					up = true;
					break;
 
				case Keyboard.DOWN:
					down = true;
					break;
 
				case Keyboard.LEFT:
					left = true;
					break;
 
				case Keyboard.RIGHT:
					right = true;
					break;
			}
 
			event.updateAfterEvent();
		}
 
		private function myOnRelease(event:KeyboardEvent):void
		{
			switch( event.keyCode )
			{
				case Keyboard.UP:
					up = false;
					break;
 
				case Keyboard.DOWN:
					down = false;
					break;
 
				case Keyboard.LEFT:
					left = false;
					break;
 
				case Keyboard.RIGHT:
					right = false;
					break;
			}
 
		}
 
	}
 
}
Download Fla Sample

Download Fla Sample

Wishlist
-Car leaves tire marks

Updates
Version 2.0 – 01/09/2011
-Re-wrote most of the code
-Fixed drifting bug
-Fixed reverse
-Added car starting rotation (just set car’s rotation property)

12 Responses

I’ve looked through this code and I can’t find where it sets the vehicle’s rotation to that strange angle.

I’ve implemented this into my own game, but my vehicle is facing the wrong direction. How do I fix this?

  • If you open the FLA you will notice Car is linked to the Car class in com.freeactionscript. That means that the car instance is using the Car class located there as its base class. Thats why at the top of “Car” its ‘public class Car extends Sprite’

    If you look down through the main loop of the game (Car.runGame) you will see the following lines which set the rotation of the MovieClip.

    Keep in mind that the word ‘this’ is refering the the instance of the car on the stage.

    radiance += (steering * speed) * .025;

    ‘radiance’, ‘steering’, and ‘speed’ are all declared at the top of the class. ‘radiance’ is just a variable to store the result of the calculation

    this.rotation = radiance * 180 / Math.PI;

    ‘this.rotation’ refers to the Car sprite’s rotation. This is then changed by the caculation radiance *180/Math.PI which is really
    ((steering*speed*0.025)*180/Math.PI

    Using this code will rotate your Car in the appropriate direction.

    To speed this code up slightly you could pre-caculate Math.PI and then use the stored result instead of caculating it every frame.

    static const PRECALC:Number = 180/Math.PI;

    then change
    this.rotation = radiance * PRECALC;

    Not much of a speed boost but every bit helps

  • its a package type .. the codes are in the folders beside it

  • how can you make it so that when the car touches the border of the level, or rocks and stuff, it doesnt allow the car through. :) thanks

  • Hi Rixeyboi,

    You should check out the Flash Game University book, it coves racing game examples.

    You can look through the source files here:
    http://flashgameu.com/book_source_files_2.html

    Try these examples:
    A3GPU212_TopDownGame.zip
    A3GPU212_RacingGame.zip

    Hope that helps.

    -PR

  • how to make a wheel mark on the path car moves can any one help me :( plssss

    • Hi hariees,

      One way to do something like that would be to draw tire marks on to one big background bitmap using BitmapData. I will add that to the wishlist, although I’m not sure when I will be able to get it done.

      You can try asking for help on AS3 forums (links on the resources page).

      Thanks,
      PR

  • i tried to write in actions on the car but i’m not able to……. :(

  • script not working

  • hi.
    anybody know ,whats the code for limiting the car movement ,at stage?
    (thats better if the car move just in our stage and not to go upper or bottom of that)

  • Leave a Reply

    You must be logged in to post a comment.