HTML and CSS Reference
In-Depth Information
init: function(props) {
this._super(_.extend(props,{
shape: 'circle',
color: 'pink',
r: 8
}));
targetCount++;
this.add('physics');
this.bind('contact',this,'checkHit');
},
checkHit: function(sprite) {
if(sprite instanceof Q.CannonBall) {
targetCount--;
this.parent.remove(this);
if(targetCount == 0) { Q.stageScene('level'); }
}
}
});
});
As expected, the code for each of the three sprites is quite short, consisting of mostly property setup code.
The Q.CannonBall class, which represents the ball fired from the cannon, has only one additional method,
countdown , which ensures that the ball is removed from the page after five seconds. It also makes the ball
fade out when there is less than 1 second left in its lifetime. The initial position x and y are set by taking the base
position of the cannon and using the passed-in dx and dy values calculated from the angle of the cannon when
it is fired.
The Q.Cannon class is defined as a cannon-like polygon. As mentioned, it doesn't need the physics
component added because it won't be partaking in any collisions but will be controlled by having its angle set.
As such the points passed in are set in such a way that rotating the polygon rotates it around the base of the
cannon because the base is set to the point 0,0. The only additional method on the cannon is the fire method,
which calculates the position of the tip of the cannon using the angle and the sin and cos methods.
If you remember your high-school geometry, cos returns a number from 0 to 1 that represents the horizontal
components of a right triangle with a hypotenuse of length 1. sin can do the same thing for the vertical com-
ponent. This means the tip of the cannon, so the starting point for the cannonball can be calculated by multiply-
ing dx and dy by the length of the cannon plus some space for the radius of the cannonball, which is exactly
what the Q.CannonBall class does.
The fire method then inserts the newly-created cannon ball into the stage and then assigns it a velocity
using the calculated dx and dy values so that the ball flies in the correct direction based on the angle of the
cannon.
Finally, the Q.Target object just creates a small, pink ball that listens for a contact event and checks if
the thing hitting it is a cannon ball. If so, it removes itself from its parent and checks if there are any targets left.
If not the level is restarted. Because the contact event happens during the world step loop, the sprite needs to be
careful not to destroy itself immediately (which is what would happen if it called this.destroy() ). Instead
it calls remove on the parent, which cues the sprite up to be removed at the end of the step.
Search WWH ::




Custom Search