简体   繁体   中英

Javascript collision detection generating score more than what it should be

I am creating a simple javascript game where a paddle needs to catch raining blocks. When there is a collision, score should increase by 1, but in my case, the score increases by 12.

I am quite sure that there is collision detection, because the block disappears when it touches the paddle and I have a console.log to show me that there is a collision.

My collision detection code

 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; } } } 

In the following piece of code, you're adding the score:

            if (objectRight>paddleX && objectLeft<paddleX+paddleWidth && objectBottom>paddleY && objectTop<paddleY+paddleHeight)
            {
                object.status = 0; 
                console.log("collision");
                score = score +1;
            }

I see you're setting the status of the object to 0. You could use this in the condition:

            if (objectRight>paddleX && objectLeft<paddleX+paddleWidth && objectBottom>paddleY && objectTop<paddleY+paddleHeight && object.status === 1)
            {
                object.status = 0; 
                console.log("collision");
                score++;
            }

Keep in mind that you're not deleting the object from the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM