在 html canvas 元素上使用 javascript 进行冲突检测,而无需使用 jquery
Collision Detection with javascript on the html canvas element without using jquery
我有一些事情无法绕开,我已经尝试了几个小时。我正在制作一个简单的游戏。我已经完成了大部分代码,但我无法使碰撞检测工作,现在无论我多么努力
.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
相关文章:
- 使用JavaScript和HTML5画布进行冲突检测
- 如何检测jQuery触发器事件完成
- 检测jquery中文本区域的自动更改
- Javascript/JQuery中的多DIV冲突检测
- three.js服务器端冲突检测错误
- 从数组绘制级别后的冲突检测
- 冲突的jQuery脚本(NoConflict修复了一个,但破坏了另一个)
- 从鼠标滚轮事件内部检测 jQuery 滚动事件
- 如何在没有固定高度时检测 jquery 中的换行符
- 检测 jQuery 中的“输入内的光标位置何时更改”
- 如何检测 jquery 移动输入滑块何时在 jquery 上移动
- 使用常规 javascript 检测 Jquery,如果不存在,则动态加载它
- 在 html canvas 元素上使用 javascript 进行冲突检测,而无需使用 jquery
- 关于不同屏幕尺寸的 Phonegap 游戏开发冲突检测
- 冲突的 jQuery 对话框脚本
- 冲突的jQuery插件
- 检测jQuery选项卡折叠事件
- JavaScript中一帧的冲突检测
- Javascript 2阵列冲突检测
- jQuery 拖动与冲突检测