Collision Detection with javascript on the html canvas element without using jquery

落爺英雄遲暮 提交于 2019-12-25 06:55:29

问题


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) {
  }
}

回答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;
    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;



回答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.

Box2dWeb



来源:https://stackoverflow.com/questions/27349650/collision-detection-with-javascript-on-the-html-canvas-element-without-using-jqu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!