Game Development Reference
In-Depth Information
You can also define a few basic operations such as adding, subtracting, multiplying, and dividing
vectors. First, let's define a method for adding a vector to an existing vector:
Vector2.prototype.addTo = function (v) {
this.x = this.x + v.x;
this.y = this.y + v.y;
return this;
};
You can use this method as follows:
var position = new Vector2(10, 10); // create a vector (10, 10)
var anotherPosition = new Vector2(20, 20); // create a vector (20, 20)
position.addTo(anotherPosition); // now represents the vector (30, 30)
The last instruction of the addTo method returns this . The reason is that you can do what's called
operator chaining . Because the addTo method returns a vector as a result, you can call methods on
that result. For example:
var position = new Vector2(10, 10); // create a vector (10, 10)
var anotherPosition = new Vector2(20, 20); // create a vector (20, 20)
position.addTo(anotherPosition).addTo(anotherPosition);
// position now represents the vector (50, 50)
Depending on the type of the parameter that is passed to the addTo method, you can do something
different. If the parameter is a number, you simply add that number to each element of the vector.
If it's a vector, you perform the operation in the way already described. One way to do this is to use
the typeof operator you've seen before, as follows:
Vector2.prototype.addTo = function (v) {
if (typeof v === 'Vector2') {
this.x = this.x + v.x;
this.y = this.y + v.y;
}
else if (typeof v === 'Number') {
this.x = this.x + v;
this.y = this.y + v;
}
return this;
};
You use an if instruction to determine the type of the parameter that was passed, and you perform
the addition operation accordingly. Another way of determining the type is to use the constructor
variable, which is part of each object in JavaScript (just like prototype is part of each function). This
is a version of the addTo method that uses the constructor variable instead of the typeof operator:
Vector2.prototype.addTo = function (v) {
if (v.constructor === Vector2) {
this.x = this.x + v.x;
this.y = this.y + v.y;
}
 
Search WWH ::




Custom Search