首页 > 解决方案 > 我的碰撞检测不起作用

问题描述

所以我正在为编程练习制作一个乒乓球游戏。其他一切似乎都有效,但碰撞检测不起作用,因为球像幻影一样穿过桨。


    player.top = player.y;
    player.right = player.x + player.width; 
    player.bottom = player.y + player.height; 
    player.left = player.x;

    ball.top = ball.y - ball.radius; 
    ball.right = ball.x + ball.radius; 
    ball.bottom = ball.y + ball.radius; 
    ball.left - ball.x - ball.radius; 

    return ball.left < player.right && ball.top < player.bottom && ball.right > player.left && ball.bottom > player.top;

}
let player = (ball.x < canvas.width / 2) ? playerOne : playerTwo; // where i'm calling the collision detection function in update
    
    if (collisionDetection(player, ball)){ 

        let angle = 0; 

        if (ball.y < (player.y + player.height / 2)){
            angle = -1 * Math.PI / 4;
        }

        else if (ball.y > (player.y + player.height / 2)){ 
            angle = Math.PI / 4;
        }

        ball.velocityX = (player === playerOne ? 1 : -1) * ball.speed * Math.cos(angle);
        ball.velocityY = ball.speed * Math.sin(angle);

        ball.speed += 0.22;

    }

我不确定是我做错了数学,还是我错误地使用了播放器变量,但无论哪种方式它都拒绝工作。

标签: javascriptpong

解决方案


我不太确定,但我认为你的

return ball.left < player.right &&
ball.top < player.bottom &&
ball.right > player.left &&
ball.bottom > player.top;

不是检查碰撞,而是检查球是否完全在球员体内。


推荐阅读