Game Development Reference
In-Depth Information
The updated example now looks like this:
// 60 times per second
window.setInterval (function(){
var td = 1.0/60;
particle.position.iadd(particle.velocity.muls(td));
}, 1000/60);
Adding checks
In JavaScript, numeric errors lead to a special NaN (not a number) value. All operations done with a NaN
as operand will result in another NaN. This can make it very difficult to track down the source of errors. In
the following example, all the variables will become NaN:
// note the missing arguments to Vec2()
var v = new Vec2(),
v2 = v.muls(2)
v3 = v2.add(new Vec2(1, 2)),
v4 = v3.subs(0.5);
// NaN, NaN
console.log(v4.x, v4.y);
In bigger applications, it can become very hard to find the origin of the NaN values. There are several
solutions to this problem. You could simply not make any mistakes or you could add assertions to all
operations. Adding assertions everywhere has its drawbacks: it's error prone, slows down, your code and
increases its size. We can, however, write a helper, as follows, that will make sure that some properties
will never become NaN by throwing an exception when they do so:
function notNaN(obj, name){
var key = '__' + name;
obj.__defineGetter__(name, function(){
return this[key];
});
obj.__defineSetter__(name, function(v) {
// you can also check for isFinite() in here if you'd like to
if(typeof v !== 'number' || isNaN(v)){
throw new TypeError(name + ' isNaN');
}
this[key] = v;
});
}
notNaN can be used on both instances and prototypes. In our case, we will apply it to the prototype of Vec2 .
When we run the following example again with notNaN in place, we will get an exception on the first line—
making it clear where the NaN values come from:
// Throw an exception if x or y of any Vec2 are set to NaN
notNaN(Vec2.prototype, 'x');
notNaN(Vec2.prototype, 'y');
 
Search WWH ::




Custom Search