Collision Detection With Javascript On The Html Canvas Element Without Using Jquery
I have something I can not wrap my head around, I have been trying for a couple of hours. I am making a simple game. I have most of the code done, but I cannot make collision detec
Solution 1:
To determine a collision in one dimension, say X, consider this example
x X ........bbb............ // Bullet b, position 8 (x=8), width 3 (X=8+3) x X ..........ttttt........ // Tank t, position 10 (x=10), width 5 (X=10+5)
a collision happens when
b.X >= t.x && b.x <= t.X
in other words
(b.x + b.width) >= t.x && b.x <= (t.x + t.width)
The same applies to the Y dimension. A collision in 2D space happens when there's one on both axes.
To spice things up I add a little prototype inheritance.
function GameObject(w, h) {
this.width = w;
this.height = h;
this.x = 0;
this.y = 0;
returnthis;
}
GameObject.prototype.collides = function (otherObject) {
return (this.x + this.width) >= otherObject.x &&
this.x <= (otherObject.x + otherObject.width) &&
(this.y + this.height) >= otherObject.y &&
this.y <= (otherObject.y + otherObject.height);
};
GameObject.prototype.move = function (x, y) {
this.x = x;
this.y = y;
returnthis;
};
function Bullet() {
return GameObject.call(this, 5, 5);
}
Bullet.prototype = new GameObject();
function Tank() {
return GameObject.call(this, 31, 31);
}
Tank.prototype = new GameObject();
Test:
var tank = newTank().move(10, 10); // 10,10 ; 41,41
var bullet = newBullet(); // 0,0 ; 5,5
bullet.move(1, 8); // 5,4 ; 10,9
console.log( bullet.collides(tank) ); // logs false;
bullet.move(5, 5); // 5,5 ; 10,10
console.log( bullet.collides(tank) ); // logs true (NE edge);
bullet.move(41, 41); // 41,41 ; 46,46
console.log( bullet.collides(tank) ); // logs true (SE edge);
bullet.move(42, 42); // 42,42 ; 47,47
console.log( bullet.collides(tank) ); // logs false;
Solution 2:
Try box2dweb, Its javascript representation of box2d library of java. It has various physics features, like collision, gravity, weight, and much more. It is simple to use and will full fill your requirements.
Post a Comment for "Collision Detection With Javascript On The Html Canvas Element Without Using Jquery"