【问题标题】:hmtl5 canvas collision with multiple objects?html5画布与多个对象的冲突?
【发布时间】:2018-11-13 06:59:33
【问题描述】:

所以我正在做一个飞扬的鸟克隆作为编码练习......现在我到了我必须检测鸟和管道之间的碰撞的部分。 考虑到我正在将管道推入数组中,我想知道您建议如何作为检测鸟与管道碰撞的最佳方法

这是代码的主要部分

 //Pipes proto that the bird most avoid
function Pipes(x1, y1, height1, width1, dx1, dy1, x2, y2, height2, 
width2, dx2, dy2) {

this.x1 = x1;
this.y1 = y1;
this.height1 = height1;
this.width1 = width1;
this.dx1 = dx1;
this.dy1 = dy1;

this.x2 = x2;
this.y2 = y2;
this.height2 = height2;
this.width2 = width2;
this.dx2 = dx2;
this.dy2 = dy2;
this.draw = function () {
    c.fillStyle = "green";
    c.fillRect(x1, y1, height1, width1)

    c.fillStyle = "green";
    c.fillRect(x2, y2, height2, width2)
}
this.update = function () {
    x1 += -dx1;
    x2 += -dx2;
    this.draw();
}
}

 function Bird(x, y, dx, dy, radius, color, flap) {
 this.x = x;
 this.y = y;
 this.dx = dx;
 this.dy = dy;
 this.radius = radius;
this.color = color;
this.draw = function () {
    c.beginPath();
    c.arc(x, y, radius, 0, 2 * Math.PI, false);
    c.fillStyle = color;
    c.fill();
};
this.update = function (){
    flap = false;
    x += dx
    //gravity manager
    var gravity = 0.4;
    y += dy
    dy += gravity;

    //Screen collision manager
    if (y + dy > innerHeight) {
        y = innerHeight - radius;
    }
    if(radius < crashObj.x1 || radius < crashObj.x2 || radius < 
     crashObj.x1){
    }
    this.draw()
}
};



//Main GameLoop
function animate() {
c.clearRect(0, 0, innerWidth, innerHeight);
//canvas Color
c.fillStyle = "#C5D3E2";
c.fillRect(0, 0, window.innerWidth, window.innerHeight);

//Updates pipes
for (var i = 0; i < pipesArr.length; i++) {
    pipesArr[i].update();
}
//draw and update bird into the screen
bird.update();

requestAnimationFrame(animate);
}

animate();

提前感谢您的回答!

【问题讨论】:

    标签: javascript arrays canvas html5-canvas game-physics


    【解决方案1】:

    您正在寻找的是圆矩形碰撞。

    User markE has posted an in-depth answer on how to achieve it,以及JS Fiddle demonstrating it

    然后在update 函数上,遍历所有Pipes 并检查它们中的每一个是否存在冲突。例如:

    for(var i = 0; i < pipesArr.length; i++){
        ...
        if(RectCircleColliding(bird, pipe)){
            die()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 2019-04-20
      • 2011-12-05
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 2015-11-16
      相关资源
      最近更新 更多