I want to add a nitro boost feature to my racing game. I want the car to go faster for 45 frames when the nitro is used, but for whatever reason I can't make it work. I originally tried using a while loop but obviously that doesn't work for JavaScript physics. Here's what I have now:

this.nitro = function() {
    if (this.hasNitro) {
        this.nitroSpeed = this.carSpeed * 2;
        this.speedCopy = this.carSpeed;
        var refreshIntervalId = setInterval(function() {
            this.carSpeed = this.nitroSpeed;
        }, 1000 / FRAMES_PER_SECOND);
this.endNitro = function(){
    this.carSpeed = this.speedCopy;
    this.hasNitro = false;

There are two cars in the game, each an instance of the car class. One of them is controlled with the arrow keys and the other is controlled with WASD. When the car's nitro button is pressed, nitro() is called on that car. The goal of the nitro is to double the car's speed for NITRO_TIME frames. When the car is initialized, nitroCount is set to NITRO_TIME.


1 Answer 1


Assuming that you have these parameters in you Car class:

this.StandardSpeed = 33; // Your own units here; set this to your liking
this.NitroFactor = 2.0;  // set this to your liking
this.NitroDuration = 45; // In frames; set this to your liking

I would suggest that once the 'nitro' button is pressed, enable a 'time left' counter to your Car object:

this.nitroFramesLeft = this.NitroDuration;

then in the 'update' method of your car (the 'move' method), apply the nitro if the counter is not zero:

var carSpeed = this.StandardSpeed;

if ( this.nitroFramesLeft > 0)
  this.nitroFramesLeft = this.nitroFramesLeft - 1;
  carSpeed = carSpeed * this.NitroFactor;

// Move the car with the modified (or not) carSpeed.

It's as simple as that :)

I've not done a lot of JavaScript in my life, so this might not be the exact syntax, but it will give you a good idea.

Also, typically, you'll want a single setInterval in your code as much as possible, and that's what is going to run your main loop.

Adding other calls to setInterval will eventually lead to headaches for debugging.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .