HTML and CSS Reference
In-Depth Information
The collision code attempts to differentiate between a “landing” and a “crash” by checking if the collision is
on the bottom of the
ship
object. If so, the method returns 1; otherwise, if the collision takes place anywhere
else on the object, it returns 2 to indicate that it's time to blow the ship up.
Now you need to update the
Ship
class to check for collisions during the
step
function. Add the following
to the top of the
step
method to stop the
Ship
in its tracks when it's dead:
step: function(dt) {
if(this.dead) return;
Next, at the bottom of that same function, add in a call to the
checkCollision
method and handle the
response appropriately:
this._super(dt);
var col;
if(col = this.checkCollision()) {
if(col == 1 && Math.abs(p.vy) < 30) {
if(p.vy > 0) {
p.vy = 0;
}
} else {
this.dead=true;
}
}
You need to verify the return value of
checkCollision
. If it returns a
1
, you collided with the bottom of
the lander, and if you go slowly, you can land. Otherwise, you mark the
Ship
as dead.
Next you'll need to modify the game code itself to grab the
backgroundPixels
for the ship to compare
against. Add the highlighted lines to scene definition in
lander.html
to read:
Q.load(['lander.png','background.png',
'lander_thrust.png','map.png'], function() {
Q.scene("level",new Q.Scene(function(stage) {
stage.insert(new Q.Sprite({ asset: "background.png" }));
stage.insert(new Q.Sprite({ asset: "map.png" }));
var ship = stage.insert(new Q.Ship({
asset: 'lander.png',
x: 10, // X Position
y: 230, // Y Position
gravity: 20, // Gravity
m: 1, // Ship's Mass
thrustX: 40, // Horizontal Thrust
thrustY: 80, // Vertical Thrust
}));
Q.backgroundPixels = Q.imageData(Q.asset('map.png'));
ship.imageData = Q.imageData(Q.asset('lander.png'));
}));