Game Development Reference
In-Depth Information
var adjacent = Math.cos(this.rotation) *
sprites.cannon_barrel.width * 0.6;
return new Vector2(this.position.x + adjacent,
this.position.y + opposite);
}
});
Just as you do with methods, you use the this keyword to refer to the object the property belongs
to. The Painter7 example belonging to this chapter adds properties to different classes. For example,
the Ball class also contains a center property. In combination with the handy methods you added
to Vector2 , you can now calculate the new position of the ball depending on the cannon rotation in a
single line of code:
this.position = Game.gameWorld.cannon.ballPosition.subtractFrom(this.center);
The nice thing about defining classes, methods, and properties is that your code becomes shorter
and much easier to understand. For example, you also add the following property to Vector2 :
Object.defineProperty(Vector2, "zero",
{
get: function () {
return new Vector2();
}
});
Now you have a very short way of creating a two-dimensional vector, as follows:
var position = Vector2.zero;
From now on, I use both properties and methods to define behavior and data access for objects.
By defining useful properties and methods in your classes, the game code becomes generally
shorter and much easier to read. For example, before you had classes with useful methods and
properties, this is how you had to calculate the ball position:
this.position = Game.gameWorld.cannon.ballPosition();
this.position.x = this.position.x - this.currentColor.width / 2;
this.position.y = this.position.y - this.currentColor.height / 2;
The new way of doing this is much shorter, as you saw earlier in this section. This effect happens
throughout the code in the games you develop in this topic, and I encourage you to embrace the
power that classes, methods, and properties provide!
Retrieving the Color of the Cannon
You define a new type called Color in this chapter. So let's use that type in combination with
a property to read and write the color of the cannon. Depending on the sprite to which the
currentColor variable points, you want to return a different color value. In order to achieve that,
you add a property called color to the Cannon class. Inside the get part of that property, you use an
 
Search WWH ::




Custom Search