2个物体的碰撞检测

时间:2014-12-11 21:00:15

标签: javascript collision

我的画布上有2辆车,我希望它在撞到另一辆车时停下来。我提出的代码似乎不起作用。我认为我如何用windowsaddevent监听器调用该函数有一个错误,但我不确定。

这是我的碰撞检测代码:

//=======================
//Car Collision Detection
//=======================

function carDetect() {
    var a = y - (car.height / 2)
    var b = y1 + (car1.height / 2) - 50;

    if (a <= b) {
    speed = 0;
    x -= 0;
    mod1 = 0;
    speed1 = 0;
    }
}

window.addEventListener("keydown", carDetect, true);
window.addEventListener("keyup", carDetect, true);

如果您愿意,我可以发送所有代码,如果您有任何问题只是评论,我会立即回答

由于

以下是我的其余代码:

//Setting the canvas and context
var canvas = document.getElementById('background');
var context = canvas.getContext('2d');

//================
//ENTER: USER CAR
//================

//Uploading car sprite
var car = new Image();
car.src = "img/Car.png";

//Setting properties of car
var x = 450;
var y = 730;
var speed = 10;
var angle = -90;
var mod = 0;

//Event listeners for keys
window.addEventListener("keydown", keypress_handler, false);
window.addEventListener("keyup", keyup_handler, false);

//Interval for animation
var moveInterval = setInterval(function () {
    draw();
}, 30);

//Drawing the car turning and changing speed
function draw() {
    context.clearRect(0, 0, canvas.width, canvas.height);

    context.save();
    context.translate(x, y);
    context.rotate(Math.PI / 180 * angle);
    context.drawImage(car, -(car.width / 2), -(car.height / 2));
    context.restore();

    drawCar();
    drawCar2();
}

//Setting the keys
function keyup_handler(event) {
    if (event.keyCode == 38 || event.keyCode == 40) {

        mod = 0;
    }
}

//Setting all of the keys
function keypress_handler(event) {
    console.log(x, y);
    if (event.keyCode == 37) {
        x -= 20;

    }
    if (event.keyCode == 39) {
        x -= -20;
    }
}

//=====================
//ENTER: OBSTACLE CAR 1
//=====================

//Uploading car
var car1 = new Image();
car1.src = "img/Car.png";

//Setting properties of car
var x1 = 450;
var y1 = 40;
var speed1 = 5;
var angle1 = 90;
var mod1 = 1;

//Interval for animation
 var moveInterval = setInterval(function () {
     drawCar();
 }, 300);

//Drawing the car turning and changing speed
function drawCar() {

          x1 += (speed1 * mod1) * Math.cos(Math.PI / 180 * angle1);
          y1 += (speed1 * mod1) * Math.sin(Math.PI / 180 * angle1);

          context.save();
          context.translate(x1, y1);
          context.rotate(Math.PI / 180 * angle1);
          context.drawImage(car1, -(car1.width / 1), -(car1.height / 1));
          context.restore();

          drawMultiple();
      drawElapsedTime();
          }        

function DrawTime() {
    if (drawElapsedTime == 2) {
         x2 += (speed2 * mod2) * Math.cos(Math.PI / 180 * angle2);
          y2 += (speed2 * mod2) * Math.sin(Math.PI / 180 * angle2);

          context.save();
          context.translate(x2, y2);
          context.rotate(Math.PI / 180 * angle2);
          context.drawImage(car2, -(car2.width / 1), -(car2.height / 1));
          context.restore();

          drawMultiple2();
    }
}


//================================
//ENTER: OBSTACLE CAR 2 Properties
//================================

//Uploading car
var car2 = new Image();
car2.src = "img/Car.png";

//Setting properties of car
var x2 = 300;
var y2 = 30;
var speed2 = 5;
var angle2 = 90;
var mod2 = 1;

function drawCar2(){
        if (parseInt((new Date() - startTime) / 1000) >= 2) {
          x2 += (speed2 * mod2) * Math.cos(Math.PI / 180 * angle2);
          y2 += (speed2 * mod2) * Math.sin(Math.PI / 180 * angle2);

          context.save();
          context.translate(x2, y2);
          context.rotate(Math.PI / 180 * angle2);
          context.drawImage(car2, -(car2.width / 1), -(car2.height / 1));
          context.restore();

          drawMultiple2();
    }
    }

//=========================
//Properties for score keep
//=========================
var score;
var theInterval = setInterval(gameStart, 200000);
var startTime;
startTime = new Date();


//===========================
//Draw Final and Elasped Time
//===========================
function drawElapsedTime() {
        context.save();
        context.beginPath();
        context.fillStyle = "black";
        context.font = "30px Verdana"
        context.fillText(parseInt((new Date() - startTime) / 1000) + " secs", canvas.width - 150, 40);
        context.restore();
    }  

function drawFinalScore() {
        // set the final score just once
        if (score == null) {
            score = parseInt((new Date() - startTime) / 1000);
        }
        context.save();
        context.beginPath();
        context.fillStyle = "black";
        context.font = "30px Verdana"
        context.fillText("Game Over: " + score + " secs", 50, 100);
        context.restore();
    }

//=======================
//Car Collision Detection
//=======================

function carDetect() {
    var a = y - (car.height / 2)
    var b = y1 + (car1.height / 2) - 50;

    if (a <= b) {
    speed = 0;
    x -= 0;
    mod1 = 0;
    speed1 = 0;
    clearInterval(theInterval);
        drawFinalScore();
    }
}

window.addEventListener("keydown", carDetect, true);
window.addEventListener("keyup", carDetect, true);


//=========================================================
//Draw Obstacle Cars from top to bottm at random positions
//=========================================================
function drawMultiple() {

    if (y1 > context.canvas.height + 150){

        y1 = -car1.height;
        x1 = Math.floor(Math.random() * 630);
        drawCar();
    }
};

//Draw the obstacle car from top to bottom
function drawMultiple2() {

    if (y2 > context.canvas.height + 150){

        y2 = -car2.height;
        x2 = Math.floor(Math.random() * 630);
        drawElapsedTime();
    }
};

//========================
//All game draw properties
//========================

function gameStart(){
    context.clearRect(0, 0, canvas.width, canvas.height);
    drawCar();
    drawCar2();
    drawMultiple();
    drawMultiple2();
    animate();
    drawElapsedTime();
}

1 个答案:

答案 0 :(得分:1)

答案取决于形状和方向。

如果它们都是盒子,那么你需要顶部,底部,左侧和右侧边缘。你可以通过两个角点得到这个。

*免责声明:(可能需要一些调试[未经测试])

In Array:
0 = Top left X
1 = Top left Y
2 = Bottom right X
3 = Bottom right Y

----------开始

var Car1 = [100, 100, 200, 200];
var Car2 = [150, 150, 250, 250];

// Will return hit result relative to first box
function isHit(obj1, obj2)
{
    var hitOnLeft = (obj1[0] <= obj2[2]) && ((obj1[1] <= obj2[3]) || (obj1[2] >= obj2[1]));
    var hitOnRight = (obj1[2] >= obj2[0]) && ((obj1[1] <= obj2[3]) || (obj1[2] >= obj2[1]));

    return hitOnLeft || hitOnRight;
}

document.write(isHit(Car1, Car2));