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.
Figure 7-6. Rocket simulation in action
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, ...
No credit card required