Game Development Reference
In-Depth Information
These functions expose the protected _angle variable and also
set the visible rotation of the car Sprite on screen.
public function get speed():Number {
return _speed;
}
public function set speed(value:Number):void {
_speed = Math.max(Math.min(value,maxSpeed),-maxSpeed);
if (Math.abs(_speed) < stoppingThreshold) _speed = 0;
}
For the speed property, since it can be negative or positive, we
use the Math min() and max() methods to force restrictions on
how high or low the speed can be. This is also where we employ
the stoppingThreshold property to truncate the speed if it becomes
infinitesimally small.
public function get acceleration():Number {
return _acceleration;
}
public function set acceleration(value:Number):void {
_acceleration = Math.max(Math.min(value,maxAcceleration),
-maxAcceleration);
}
Much like the speed methods, we use min() and max() again to
set the limits for the acceleration property. That is all that is
required in the Vehicle class for now. Here, it is in its entirety.
package drivingsim {
import flash.display.Sprite;
public class Vehicle extends Sprite{
static public const maxAcceleration:Number = 100;
static public const maxSpeed:Number = 350;
static public const maxSteering:Number = Math.PI / 40;
static public const accelerationRate:Number = 50;
static public const handBrakeFriction:Number = .75;
static public const stoppingThreshold:Number = 0.1;
protected var _speed:Number = 0;
protected var _acceleration:Number = 0;
protected var _angle:Number = 0;
public function Vehicle() {
}