Game Development Reference
In-Depth Information
You can now create an object as follows:
var position = new Vector2(0,0);
It would be nice if somehow you could initialize a vector without having to pass both parameters all
the time. One way to do this is to check whether x and/or y is undefined. If that is the case,
you simply initialize the member variable to 0, as follows:
function Vector2(x, y) {
if (typeof x === 'undefined')
this.x = 0;
else
this.x = x;
if (typeof y === 'undefined')
this.y = 0;
else
this.y = y;
}
The typeof keyword is used in JavaScript to return the type of a variable. Here you use it to check
whether x and y have a defined type. If that is the case, you assign the value passed as a parameter
to the member variable. Otherwise, you assign the value 0. JavaScript knows a shorter version of
writing down such if instructions. This is what the same method looks like, but shortened:
function Vector2(x, y) {
this.x = typeof x !== 'undefined' ? x : 0;
this.y = typeof y !== 'undefined' ? y : 0;
}
This code does exactly the same thing as the version with the full if instructions, but it's a lot
shorter. In front of the question mark is the condition. Then, after the question mark, there are the
two options for the values, separated by a colon. When using this shorter version, make sure your
code is still readable. This topic uses the shorter version only to check whether parameters are
defined. This has advantages; for example, you can create Vector2 objects in various ways:
var position = new Vector2(); // create a vector (0, 0)
var anotherPosition = new Vector2(35, 40); // create a vector (35, 40)
var yetAnotherPosition = new Vector2(-1); // create a vector (-1, 0)
Now you can add a few useful methods to the Vector2 class so it becomes easier to perform
calculations with vectors. For example, the following method makes a copy of a vector:
Vector2.prototype.copy = function () {
return new Vector2(this.x, this.y);
};
This is handy if you want to copy positions or velocities from different game objects. Also, comparing
vectors is useful. The equals method does this for you:
Vector2.prototype.equals = function (obj) {
return this.x === obj.x && this.y === obj.y;
};
 
Search WWH ::




Custom Search