Game Development Reference
In-Depth Information
protected function moveVehicle():void {
if (!vehicle.acceleration) vehicle.speed *= _friction;
vehicle.speed += vehicle.acceleration;
vehicle.x += Math.cos(vehicle.angle) * (vehicle.speed *
Time.deltaTime);
vehicle.y += Math.sin(vehicle.angle) * (vehicle.speed *
Time.deltaTime);
}
While only four lines, this method does a great deal. First, it
applies friction to the vehicle
s speed if it is not accelerating; not
doing so would cause the vehicle to continue moving as though it
were one a very slick surface. The vehicle
'
s speed is then increased
by its acceleration. The last two lines then compute the vehicle
'
s
new x and y coordinates based on the angle the car is facing and the
speed at which it is traveling. Note that both this method and
the readInput method use Time.deltaTime property to only apply the
speed that is necessary for the amount of time that has passed. By
using this method, the framerate of the SWF can now change, either
deliberately or accidentally, without consequence to the responsive-
ness of the simulation. Let
'
'
s review the Game class in its entirety.
package drivingsim {
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
public class Game extends Sprite {
protected var _leftPressed:Boolean;
protected var _rightPressed:Boolean;
protected var _upPressed:Boolean;
protected var _downPressed:Boolean;
protected var _spacePressed:Boolean;
protected var _friction:Number = .95;
public var vehicle:Vehicle;
public function Game() {