打砖块游戏弹跳功能

时间:2019-04-20 13:54:30

标签: javascript canvas collision-detection

我目前正在使用JavaScript构建破砖游戏。我正在努力使球碰到球拍时反弹。我不太了解涉及到的数学知识,希望能对您有所帮助。

我尝试了多种方法来创建一个演示此功能的函数,并查看了许多已经打开的Stack Overflow讨论,但无济于事。

canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
//ball co-ordinates and speed
var ballX = 400;
var ballY = 300;
var ballSpeedX = 4;
var ballSpeedY = -12;

//paddle co-ordinates
var paddleX = 350;
var paddleY = 550;

var canvas;
var canvasContext;

//consts
const PADDLE_HEIGHT = 13;
const PADDLE_THICKNESS = 100;

window.onload = function() {
    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');
    var framesPerSecond = 30;
    setInterval(callBoth, 1000 / framesPerSecond);

    canvas.addEventListener('mousemove', function(evt) {
        var mousePos = calculateMousePos(evt);
        paddleX = mousePos.x - PADDLE_HEIGHT / 2; //	minus	half	height,	to	center	it
    });
};

function calculateMousePos(evt) {
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {
        x: mouseX,
        y: mouseY
    };
}

function drawEverything() {
    // canvas
    colorRect(0, 0, canvas.width, canvas.height, 'black');

    //paddle
    colorRect(paddleX, paddleY, PADDLE_THICKNESS, PADDLE_HEIGHT, 'blue');

    //ball
    canvasContext.fillStyle = 'white';
    canvasContext.beginPath();
    canvasContext.arc(ballX, ballY, 7, 0, Math.PI * 2, true);
    canvasContext.fill();
}

function callBoth() {
    moveEverything();
    drawEverything();
}

function moveEverything() {
    ballX = ballX + ballSpeedX;
    ballY = ballY + ballSpeedY;

    if (ballX > canvas.width || ballX < 0) {
        ballSpeedX = -ballSpeedX;
    }

    if (ballY > canvas.height || ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }

    /*Here is where I would want the code for the ball bouncing off of the   
paddle to be.*/
}

function colorRect(leftX, topY, width, height, drawColor) {
    canvasContext.fillStyle = drawColor;
    canvasContext.fillRect(leftX, topY, width, height);
}
<canvas id='gameCanvas' width='800' height='600'></canvas>

我要寻找的是,当球与球拍的X和Y坐标接触时,球会弹起。

0 个答案:

没有答案