Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1

Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples


The .applyBrake() method takes the object’s speed state variable and subtracts a braking factor from
the current speed, which causes the object to decelerate, or to brake. This is done by taking the object’s
current speed setting and subtracting the brakingFactor from it and then setting the result of the subtraction
back to the original speed variable so that the object’s speed state now contains the updated (decelerated)
braking value.


void applyBrake (int brakingFactor) {
speed = speed - brakingFactor;
}


The .turnWheel() method is straightforward, much like the .shiftGears() method, except that it uses a
String value of N, S, E, or W to control the direction that the car turns. When .turnWheel(“W”) is used, a Car
object will turn to the left. When .turnWheel(“E”) is used, the car will turn to the right, given, of course, that
the car object is currently heading to the north, which according to its default direction setting, it is.


void turnWheel (String newDirection) {
direction = newDirection;
}


The methods that make a Car Object function go inside the class, after the variable declarations, as
follows:


class Car {
int speed = 15;
int gear = 1;
int drivetrain = 4;
String direction = "N";
String color = "Red";
String fuel = "Gas";


void shiftGears (int newGear) {
gear = newGear;
}


void accelerateSpeed (int acceleration) {
speed = speed + acceleration;
}


void applyBrake (int brakingFactor) {
speed = speed - brakingFactor;
}


void turnWheel (String newDirection) {
direction = newDirection;
}
}


This Car class will allow you to define a Car object, even if you don’t specifically include the Car()
constructor method, which we will cover next. This is why your variable settings will become your Car object
defaults. It is best to code your own constructor method, however, so that you take total control over your
object creation and so that you don’t have to pre-initialize your variables to one value or another. Therefore,

Free download pdf