Game Development Reference
In-Depth Information
else if (v.constructor === Number) {
this.x = this.x + v;
this.y = this.y + v;
}
return this;
};
The
addTo
method adds a vector to an existing vector. You can also define an
add
method that adds
two vectors and returns a
new vector
. To do that, you can reuse the
copy
and
addTo
methods:
Vector2.prototype.add = function (v) {
var result = this.copy();
return result.addTo(v);
};
You can now do the following:
var position = new Vector2(10, 10); // create a vector (10, 10)
var anotherPosition = new Vector2(20, 20); // create a vector (20, 20)
var sum = position.add(anotherPosition); // creates a new vector (30, 30)
In this example,
position
and
anotherPosition
are unchanged in the third instruction. A new vector
object is created that contains the sum of the values in the operand vectors.
Take a look at the
Vector2.js
file in the Painter6 example, where you can see the full definition of
the
Vector2
class. It defines the most common vector operations in this class, including the addition
methods discussed in this section. As a result, using vectors in the Painter game is much easier.
You use the
Vector2
type in all the game objects to represent positions and velocities. For example,
this is the new constructor of the
Ball
class:
function Ball() {
this.position = new Vector2();
this.velocity = new Vector2();
this.origin = new Vector2();
this.currentColor = sprites.ball_red;
this.shooting = false;
}
Thanks to the methods in the
Vector2
class, you can intuitively update the ball position according to
its velocity, in a single line of code:
this.position.addTo(this.velocity.multiply(delta));
Default Values for Parameters
Before completing this chapter, let's have one more look at how the
Vector2
constructor is defined:
function Vector2(x, y) {
this.x = typeof x !== 'undefined' ? x : 0;
this.y = typeof y !== 'undefined' ? y : 0;
}
Search WWH ::
Custom Search