HTML and CSS Reference
In-Depth Information
To keep the inner loop a little simpler, you can precalculate the starting location of the Ship in relation to the
background pixel data. You do this, as shown in Listing 17-8 , and stick it in the variable bgOffset . Add the
following checkCollision method to the Ship class.
Listing 17-8: Checking collision between ship and background
checkCollision: function() {
var bgData = Q.backgroundPixels;
// Get a integer based position from our
// x and y values
var bgx = Math.floor(this.p.x);
var bgy = Math.floor(this.p.y);
// Calculate the initial offset into our background
var bgOffset = bgx * 4 + bgy * bgData.width * 4 + 3;
// Pull out our data easy access
var pixels = this.imageData.data;
var bgPixels = bgData.data;
for(var sy=0;sy < this.imageData.height;sy++) {
for(var sx=0;sx < this.imageData.width;sx++) {
// Check for an existing pixel on our ship
if(pixels[sx*4 + sy * this.imageData.width * 4 + 3]) {
// Then check for a matching existing pixel
// on the background starting from our bgOffest
// and then indexing in from there
if(bgPixels[bgOffset + sx*4 + sy * bgData.width * 4]) {
// Next check if we are at the bottom of the lander
// if so return 1, to indicate that we might be
landing
// instead of crashing
if(sy > this.imageData.height - 2) {
return 1;
} else {
// Otherwise return 2 and...Boom!
return 2;
}
}
}
}
}
return 0;
}
 
 
Search WWH ::




Custom Search