Creative HTML5 and JavaScript Asteroid Game

Today in this post, jsB@nk want to present to you a simple JavaScript application made by HTML5; name of this web-based JavaScript game is Asteroid, and tips to play: we just need to use the arrow keys to move your character (triangle-shape spacecraft) to avoid asteroids moving randomly on around.

Especially, this JavaScript Asteroid game is built totally with HTML5 techniques (by using canvas object) - a good JavaScript example code to help us to reach this new technology easily.

Learn more about HTML5 through other JavaScript article tutorials, other JavaScript example codes on the jsB@nk:
- JavaScript Image Rotation script with CANVAS in HTML5
- Awesome Canvas Drawer with HTML5
- HOT New JavaScript APIs with HTML5
- 12 Awesome and Creative JavaScript Games you should try


Sampled by © JavaScriptBank.com

Play in new window

By way of brain dump, and so that I've got a record of the stuff I need to remember somewhere, here's just list of bits that I picked up throughout the day. Obviously there was tons more, but when you're coding, listening, learning and wrapping your head around trig (something that I'm quite useless at) - less notes are taken ;-)

Canvas

For an animation the (pseudo) code looks like this:

var mouseX = 0, mouseY = 0, mouseDown = false, keys = {};
setup
(); // initalisation
setInterval
(loop, 1000 / 60); // 60 fps

function loop() {
 
// 1. handle key or mouse states
 
// 2. update position of animated objects: particles, etc
 
object.update();
 
// 3. draw each object
 
object.draw();
}

// capture events, but don't do anything with them
document
.addEventListener('mousemove', function (e) {
  mouseX
= e.pageX;
  mouseY
= e.pageY;
}, false);

Vectors

Instead of:

var distance = Math.sqrt((this.diff.x * this.diff.x) + (this.diff.y*this.diff.y));
return (distance<this.radius);

Use:

var distanceSq = (this.diff.x * this.diff.x) + (this.diff.y*this.diff.y);
return (distanceSq < this.radius * this.radius)

3D

Collision detection in 3D:

var distanceSq3D = (this.diff.x * this.diff.x) + (this.diff.y*this.diff.y) + (this.diff.z * this.diff.z)
return (distanceSq3D < this.radius * this.radius)

To get the z-order correct (painters algorithm), you need to sort by the z axis, where points is an array of objects with xyz:

points = points.sort(function (a, b) {
 
return a.z >= b.z ? -1 : 1;
});

Optimisation tricks

To get a circular distribution, rotate around a circle using:

x = Math.sin(angle) * speed; // sin for X
y
= Math.cos(angle) * speed; // cos for Y

2000+ free JavaScripts
at www.JavaScriptBank.com