在 html canvas 元素上使用 javascript 进行冲突检测,而无需使用 jquery

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

本文关键字:冲突检测 jquery javascript canvas html 元素      更新时间:2023-09-26

我有一些事情无法绕开,我已经尝试了几个小时。我正在制作一个简单的游戏。我已经完成了大部分代码,但我无法使碰撞检测工作,现在无论我多么努力

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

要确定一个维度上的碰撞,比如 X,请考虑此示例

       x X              ........bbb............//项目符号 b,位置 8 (x=8),宽度 3 (x=8+3)          x X..........ttttt........//坦克 t,位置 10 (x=10),宽度 5 (x=10+5)

发生碰撞时

b.X >= t.x && b.x <= t.X

换句话说,在

(b.x + b.width) >= t.x && b.x <= (t.x + t.width)

这同样适用于 Y 维度。当两个轴上都有一个时,2D 空间中会发生碰撞。

为了给事情增添趣味,我添加了一些原型继承。

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();

测试:

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;

试试box2dweb,它的javascript表示的java的box2d库。它具有各种物理功能,例如碰撞,重力,重量等等。它使用简单,可以完全满足您的要求。

Box2dWeb