Harry
Harry

Reputation: 33

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 detection work, now matter how hard I try

JS

function collision() {
//Tank1
if (bulcords2.x < tankcords.x + 31 &&
    bulcords2.x + 5 > tankcords.x &&
    bulcords2.y < tankcords.y + 31 &&
    1 + bulcords2.y > tankcords.y) {
  }
}

Upvotes: 1

Views: 523

Answers (2)

Tomalak
Tomalak

Reputation: 338228

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;
    return this;
}
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;
    return this;
};
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 = new Tank().move(10, 10); // 10,10 ; 41,41
var bullet = new Bullet(); // 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;

Upvotes: 1

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

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.

Box2dWeb

Upvotes: 1

Related Questions