Game Development Reference
In-Depth Information
You can actually shorten the code you've written a little. Why add an initialize method when Ball itself
already is a function that is called? You can simply perform the initialization in that function, as follows:
function Ball() {
this.position = { x : 0, y : 0 };
this.velocity = { x : 0, y : 0 };
this.origin = { x : 0, y : 0 };
this.currentColor = sprites.ball_red;
this.shooting = false;
}
Now when you create balls, they're initialized on creation:
var ball = new Ball();
var anotherBall = new Ball();
And since Ball is a function, you can even pass along parameters if you want to:
function Ball(pos) {
this.position = pos;
this.velocity = { x : 0, y : 0 };
this.origin = { x : 0, y : 0 };
this.currentColor = sprites.ball_red;
this.shooting = false;
}
var ball = new Ball({ x : 0, y : 0});
var anotherBall = new Ball({ x : 100, y : 100});
Because the Ball function is responsible for initializing (or constructing ) the object, this function is
also called the constructor . The constructor together with the methods defined in the prototype is
called a class . When an object is created according to a class, you also say that the object has that
class as a type . In the previous example, the ball object has as a type Ball , because it was created
using the Ball constructor and its prototype. A class is a blueprint for an object, and as such it
describes two things:
The data that is contained within an object. In the case of balls, this data
consists of a position, a velocity, an origin, the current color, and a variable
indicating whether the ball is shooting. Generally, this data is initialized in the
constructor.
manipulate the data. In the Ball class, these methods are the
game-loop methods ( handleInput , update , draw , and reset ).
You can very easily translate the game-loop methods as methods in the Ball prototype, simply by
replacing ball with this . For example, here is the handleInput method:
The methods that
Ball.prototype.handleInput = function (delta) {
if (Mouse.leftPressed && !this.shooting) {
this.shooting = true;
this.velocity.x = (Mouse.position.x - this.position.x) * 1.2;
this.velocity.y = (Mouse.position.y - this.position.y) * 1.2;
}
};
 
Search WWH ::




Custom Search