HTML and CSS Reference
In-Depth Information
step: function(dt) {
var bgData = Q.backgroundPixels;
var pixels = bgData.data;
for(var i =0,len=this.particles.length;i<len;i++) {
var v = this.particles[i];
if(v.lifetime > 0) {
var oldx = v.x, oldy = v.y;
v.vy += 20 * dt;
v.x += dt * v.vx;
v.y += dt * v.vy;
var loc = Math.floor(v.x)*4 + Math.floor(v.y) * bgData.width * 4;
if(pixels[loc + 3]) {
v.x = oldx;
v.y = oldy;
v.vy *= -0.2;
v.vx *= -0.2;
}
v.lifetime-=dt;
}
if(v.lifetime <= 0) { Q.stageScene('level'); return; }
}
},
To determine the offset location (stored in the loc variable) into the pixels array, you need to use the
Math.floor method. The reason for this is that the particle's position is represented by floating point num-
bers that won't fall on integer boundaries. To index into the array, those numbers need to be converted to in-
tegers. Math.floor does that by taking an arbitrary floating-point number and chopping off any decimals to
return an integer.
If you run the game, or run lander_explosion.html from the chapter code, you should now have a
ship that blows up into a number of different particles when it dies.
Summary
Canvas makes it possible to play around with pixel data directly. Although this is a feature that isn't used often,
it can be useful for a number of different circumstances in which you need pixel-perfect collisions or Can-
vas post-processing. However, be careful with how much per-pixel processing you use because many mobile
devices are lighter on CPU horsepower than their desktop cousins, and you must be careful not to overload
them.
Search WWH ::




Custom Search