基本的乒乓球游戏-球反弹时将球拍宽度考虑在内

时间:2018-09-28 01:39:56

标签: javascript pong

我很难让球识别桨的厚度(在画布的每一侧一个),因此目前,当球击中桨时,球会穿过桨(尽管球会对桨的存在做出反应)划桨),然后从画布的边缘弹回,而不是从划桨的前端弹起。

桨的变量,常量和桨的尺寸

var paddle1Y = 250;
var paddle2Y = 250;
const PADDLE_THICKNESS = 10;
const PADDLE_HEIGHT = 100;

    // this is left player paddle
colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'red');

// this is right computer paddle
colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT,'red');

// next line draws the ball
colorCircle(ballX, ballY, 10, 'white');

canvasContext.fillText(player1Score, 100, 100);
canvasContext.fillText(player2Score, canvas.width-100, 100);
}

球对桨做出反应

computerMovement();

ballX = ballX + ballSpeedX;
ballY = ballY + ballSpeedY;

if(ballX < 0 - PADDLE_THICKNESS) {
    if(ballY > paddle1Y &&
        ballY < paddle1Y+PADDLE_HEIGHT) {
        ballSpeedX = -ballSpeedX;

        var deltaY = ballY
                -(paddle1Y+PADDLE_HEIGHT/2);
        ballSpeedY = deltaY * 0.35;
    } else {
        player2Score++; // must be BEFORE ballReset()
        ballReset();
    }
}
if(ballX > canvas.width + PADDLE_THICKNESS) {
    if(ballY > paddle2Y &&
        ballY < paddle2Y+PADDLE_HEIGHT) {
        ballSpeedX = -ballSpeedX;

        var deltaY = ballY
                -(paddle2Y+PADDLE_HEIGHT/2);
        ballSpeedY = deltaY * 0.35;
    } else {
        player1Score++; // must be BEFORE ballReset()
        ballReset();    
    }
}

所以基本上,我需要球的X位置(ballX)看起来像从弹跳板的两侧弹起,而不是从画布的边缘弹起,然后弹回。有什么想法需要增加以使球考虑桨的厚度吗? 谢谢。

0 个答案:

没有答案