Game Development Reference
In-Depth Information
Adding a Button to Show a Help Frame
This section explains how to add a button to a game, which you use to display a help frame. To do
that, you add another class, Button , to the program. You inherit from the SpriteGameObject class
and add some simple behavior that checks whether the player pressed a button. In the Button class,
you declare a boolean member variable that indicates whether the button was pressed. Then you
override the handleInput method to check whether the player has clicked the left mouse button or
has touched the button on the screen. If the mouse or touching position is within the boundaries
of the sprite at that time, you know the player has pressed the button, and you set the value of the
member variable to true . How can you check whether the mouse position is within the boundaries
of the sprite? By using the Rectangle class. As a first step, you construct a Rectangle object that
encompasses the sprite. The position of this rectangle should be the world position of the sprite
minus its origin. The width and height of the rectangle are the same as the width and height of the
sprite. For convenience, let's add a property to SpriteGameObject called boundingBox that calculates
this rectangle for you:
Object.defineProperty(SpriteGameObject.prototype, "boundingBox",
{
get: function () {
var leftTop = this.worldPosition.subtractFrom(this.origin);
return new Rectangle(leftTop.x, leftTop.y, this.width,
this.height);
}
});
You have to use the world position here, because you want to check whether the mouse pointer
or the touch is within the sprite at its actual, world position. You add a simple method contains to
Rectangle , which checks whether a point is inside the rectangle:
Rectangle.prototype.contains = function (v) {
v = typeof v !== 'undefined' ? v : new Vector2();
return (v.x >=this.left && v.x <= this.right &&
v.y >=this.top && v.y <= this.bottom);
};
The first line of this code checks whether the parameter v has been defined. If it hasn't, you simply
assign it the zero vector. You then check whether the x value lies between the left and right side of
the rectangle and the y value lies between the top and bottom.
You also add methods to the Mouse and Touch classes that can help solve your problem easily.
For example, this is the method for checking whether the player pressed the left mouse button
within a given rectangle:
Mouse_Singleton.prototype.containsMousePress = function (rect) {
return this._left.pressed && rect.contains(this._position);
};
 
Search WWH ::




Custom Search