Useful JavaScript Game Extensions: Number#sign and Number#abs

Part 11 and 12

In an object oriented perspective it can be useful to think of numbers as objects. Why have to deal with “everything is an object, except numbers, those are different and require special methods”, when you can have a more consistent programing environment where numbers are objects too, and have the same interfaces and methods you’d expect.

JavaScript’s prototype based inheritance is perfect for extending the behavior various types of objects, and fortunately for us, unlike in Java, in JavaScript numbers really are objects. Though unfortunately for us, as is usual in JavaScript, the API is seriously lacking.

Getting the sign of a number can often be useful in games. For example, I wanted to have camera tracking where the camera would look ahead by the square of the velocity of the object. But if the object were moving in the negative direction the squaring would obliterate the sign. Number#sign to the rescue!

/**
 * @returns The sign of this number, 0 if the number is 0.
 */
Number.prototype.sign = function() {
  if(this > 0) {
    return 1;
  } else if (this < 0) {
    return -1;
  } else {
    return 0;
  }
}
 
// Example, using the sign to maintain direction when squaring
var weightedX = dinoPosition.x + (1.25 * dinoVelocity.x * dinoVelocity.x * dinoVelocity.x.sign());

Another useful number method is abs. Why do you need some external object to get the absolute value of a number? Shouldn’t a number know it’s own absolute value? Now they can:

/**
 * @returns The absolute value of the number.
 */
Number.prototype.abs = function() {
  return Math.abs(this);
};

I’m not always against the prototype feature of JavaScript, just against using prototype based inheritance to simulate class and module based inheritance. Stick around towards the end of the series to see some great examples.

See you next time!

One thought on “Useful JavaScript Game Extensions: Number#sign and Number#abs

  1. Pingback: Useful JavaScript Game Extensions: Number#round

Leave a Reply

Your email address will not be published. Required fields are marked *