Hmtl5 холст столкновение с несколькими объектами? - PullRequest
0 голосов
/ 04 июня 2018

Итак, я делаю клон «летучей птицы» как упражнение по кодированию… и теперь я дошел до того места, где мне нужно обнаружить столкновение между птицей и трубами.Я хотел бы знать, как бы вы предложили, чтобы быть лучшим способом обнаружения столкновения птицы с трубами, учитывая, что я помещаю трубы в массив

, это основные части кода

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

заранее спасибо за ответ!

1 Ответ

0 голосов
/ 06 июня 2018

То, что вы ищете, это столкновение круг-прямоугольник.

Пользователь markE опубликовал подробный ответ о том, как его достичь , вместе с JS Fiddle, демонстрирующим его .

Затем наupdate, пройдите все Pipes и проверьте каждый из них на предмет столкновения.Например:

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