html5画布中播放器和对象之间的碰撞

时间:2018-01-16 16:08:08

标签: javascript html5 canvas

我正在使用html5和javascript进行比赛。但是我正在努力应对碰撞。 汽车应该在撞到其中一个物体时停下来。

car = player
ctxbigrect = object

这是我在网站上找到的代码,但它似乎不适用于我的游戏:

if (
      car.x < ctxbigrect.x + ctxbigrect.width 
   && car.x + car.width > ctxbigrect.x 
   && car.y < ctxbigrect.y + ctxbigrect.height 
   && car.height + ctxbigrect.y > ctxbigrect.y) 
{
   console.log("collision detected");
} else {
   console.log("no collision detected");
}

如果有人可以帮助我的话,我会非常赞赏它。

1 个答案:

答案 0 :(得分:0)

如果您更合乎逻辑地标记您的积分,那么更容易思考。老实说,如果你画一幅画,它会对你有很大的帮助。下面的演示可以帮助你。

//setup logical names for the points
let carLeft = car.x, 
carTop = car.y, 
carRight = car.x + car.width, 
carBottom = car.y + car.height;

let boxLeft = box.x, 
boxTop = box.y, 
boxRight = box.x + box.width, 
boxBottom = box.y + box.height;

//we check if the car is within the radius of the box at all
//is it past the left border but not the right hand side, 
//or is it below the top line and above the bottom, 
//or is the right of the car within the left and right lines of the box 
//or is the bottom of the car within the bottom and top of the box

if(carLeft >= boxLeft && carLeft <= boxRight || 
carTop < boxTop && carTop > boxBottom || 
carRight >= boxLeft && carRight <= boxRight ||
carBottom >= box.bottom && carBottom <= box.top) {
//...do whatever
}

&#13;
&#13;
let c = document.querySelector("#myCanvas"), ctx = c.getContext("2d"), car = {
x: 0,
y: 5, 
width: 20,
height: 10
}, box = {
x: 0,
y: 0,
width: 30,
height: 30
}, flag = false;

function draw() {
ctx.beginPath();
ctx.clearRect(0,0,window.innerWidth, window.innerHeight);
ctx.fillRect(car.x, car.y, car.width, car.height);
ctx.fillStyle = "rgba(0,250,0, .3)";
ctx.fillRect(box.x, box.y, box.width, box.height);

let carLeft = car.x, carTop = car.y, carRight = car.x + car.width, carBottom = car.y + car.height;
let boxLeft = box.x, boxTop = box.y, boxRight = box.x + box.width, boxBottom = box.y + box.height;


if(carLeft >= boxLeft && carLeft <= boxRight || carTop < boxTop && carTop > boxBottom || carRight >= boxLeft && carRight <= boxRight || carBottom >= box.bottom && carBottom <= box.top) {
console.log("hit ", box, car);
}

if(!flag && box.x < 200) box.x++; 
if(box.x === 200) flag = true; 
if(flag && box.x > 0) box.x--;
if(flag && box.x === 0) flag = false;
requestAnimationFrame(draw);
}
draw();
&#13;
<canvas id="myCanvas">
&#13;
&#13;
&#13;