首页 > 解决方案 > Brick Breaker 游戏弹跳功能

问题描述

我目前正在使用 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 坐标接触时,它会反弹。

标签: javascriptcanvascollision-detection

解决方案


推荐阅读