We already have rudimentary throttle control, in that we can set the throttle to maximum forward or maximum reverse, but we need finer control than that for our game. We'll create a new method for this:
cycleControl()
method, add a new method that looks like the following code:def adjustThrottle(self, dir, dt): if(dir == "up"): self.throttle += .25 * dt if(self.throttle > 1 ): self.throttle = 1 else: self.throttle -= .25 * dt if(self.throttle < -1 ): self.throttle = -1
cycleControl()
method:else: self.throttle = 0
adjustThrottle()
method. Change the line that sets self.throttle = 1
to:self.adjustThrottle("up", dt)
self.throttle = -1
to:self.adjustThrottle("down", dt)
chp04_04.py
in the Chapter04/Examples
folder, if you need to see the code. chp04_04.py
and run it.This time the cycle didn't stop when we released the keyboard keys. That's because the position of the throttle is being saved. Let's take a look at the adjustThrottle()
method to see how it works:
def adjustThrottle(self, dir, dt): if(dir == "up"): self.throttle += .25 * dt if(self.throttle > 1 ): self.throttle = 1 else: self.throttle -= .25 * dt if(self.throttle < -1 ): self.throttle = -1
First, we accept two variables other than self. dt
. We should recognize that dir
just tells the method whether we are adjusting the throttle up or down. We start the method with an if
statement to determine the direction we're adjusting the throttle in, and then we adjust it by 0.25 per second. After the adjustments, we check to see if it has gone outside the limit of -1 to 1, and if so, we set it to the limit.