碰撞检测使用javascript在html canvas元素上而不使用jquery [英] Collision Detection with javascript on the html canvas element without using jquery

查看:204
本文介绍了碰撞检测使用javascript在html canvas元素上而不使用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) {
  }
}


推荐答案

一个维度,比如X,考虑这个例子。

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)

碰撞发生在

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

换句话说

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

这同样适用于Y维度。

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

测试:

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;

这篇关于碰撞检测使用javascript在html canvas元素上而不使用jquery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆