我正在创建一个简单的JavaScript游戏,桨需要抓住下雨的块。发生碰撞时,分数应增加1,但在我的情况下,分数应增加12。
我非常确定有碰撞检测功能,因为该块在碰到桨时便消失了,并且我有一个console.log告诉我有碰撞。
我的碰撞检测代码
var spawnRate = 1500;
var spawnRateOfDescent = 2;
var lastSpawn = -10;
var objects = [];
var startTime = Date.now();
var score =0;
function spawnRandomObject() {
var t;
if (Math.random() < 0.50)
{
t = "red";
}
else
{
t = "blue";
}
var object = {
type: t,
x: Math.random() * (canvas.width - 30) + 15,
y: 100,
r: 8,
status: 1
}
objects.push(object);
}
function animate()
{
var time = Date.now();
if (time > (lastSpawn + spawnRate)) {
lastSpawn = time;
spawnRandomObject();
}
var paddleLeft=paddleX;
var paddleRight=paddleX+paddleWidth;
var paddleTop=paddleY;
var paddleBottom=paddleY+paddleHeight;
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
object.y += spawnRateOfDescent;
if (object.status == 1){ //only draw the ball if the status is 1
ctx.beginPath();
ctx.arc(object.x, object.y, object.r, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = object.type;
ctx.fill();
}
var objectTop=object.y-object.r;
var objectBottom=object.y+object.r;
var objectLeft=object.x-object.r;
var objectRight=object.x+object.r;
if (objectRight>paddleX && objectLeft<paddleX+paddleWidth && objectBottom>paddleY && objectTop<paddleY+paddleHeight)
{
object.status = 0;
console.log("collision");
score = score +1;
}
}
}
答案 0 :(得分:0)
在下面的代码中,您要添加分数:
if (objectRight>paddleX && objectLeft<paddleX+paddleWidth && objectBottom>paddleY && objectTop<paddleY+paddleHeight)
{
object.status = 0;
console.log("collision");
score = score +1;
}
我看到您正在将对象的status
设置为0。您可以在以下条件下使用它:
if (objectRight>paddleX && objectLeft<paddleX+paddleWidth && objectBottom>paddleY && objectTop<paddleY+paddleHeight && object.status === 1)
{
object.status = 0;
console.log("collision");
score++;
}
请记住,您不是要从数组中删除对象。