Cover by Raffaele Cecco

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Rocket Simulation

The following rocket simulation (Figure 7-6) is a more elaborate demonstration of the use of vectors. The simulation features a steerable rocket and colorful obstacles to avoid. The rocket rotates to face the mouse pointer, and you can apply engine thrust in the facing direction of the rocket by holding down the left mouse button. The simulation is gravity and friction-free, so it requires dexterous use of the mouse to keep the rocket traveling in the desired direction. The same vector object we defined earlier in the cannon example is used throughout.

Rocket simulation in action

Figure 7-6. Rocket simulation in action

The Game Object

We use functional inheritance in the rocket simulation to create both the rocket and obstacles from a base object called gameObject, which provides common methods and properties:

var gameObject = function (x, y, radius, mass) {
    var that = {
        x: x,
        y: y,
        vel: vector2d(0, 0),
        radius: radius,
        mass: mass,
        removeMe: false,

        move: function () {
            that.x += that.vel.vx;
            that.y += that.vel.vy;
            if (that.vel.vx < 0 && that.x < −50) {
                that.x += canvas.width + 100;
            } else if (that.vel.vx > 0 && that.x > canvas.width + 50) {
                that.x −= canvas.width + 100;
            }
            if (that.vel.vy < 0 && that.y < −50) {
                that.y += canvas.height + 100;
            } else if (that.vel.vy > 0 && that.y > canvas.height + 50) {
                that.y −= canvas.height + 100;
            }
        },

        draw: function () {
            return;
        }
    };
    return that;
};

Essentially, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required