diff --git a/src/main.js b/src/main.js index 1685f14..e0a7b27 100644 --- a/src/main.js +++ b/src/main.js @@ -11,6 +11,7 @@ import { PADDLE_HEIGHT, PADDLE_WIDTH, } from './config'; +import { calculateCollision } from './lib/calculateCollision/calculateCollision'; (async () => { // Create a new application @@ -60,18 +61,42 @@ import { const topBoundary = BALL_RADIUS; const bottomBoundary = CONTAINER_HEIGHT - BALL_RADIUS; const paddleTop = CONTAINER_HEIGHT - PADDLE_HEIGHT; + const bricksBottom = BRICK_HEIGHT; let horizontalSpeed = BALL_SPEED * Math.cos(BALL_INITIAL_ANGLE); let verticalSpeed = -1 * BALL_SPEED * Math.sin(BALL_INITIAL_ANGLE); app.ticker.add((time) => { - // Не даем выйти за границы стен слева / справав и меняем направление + // Базоввое взаимодействие мяча и кирпича + for (let i = bricksRow.length - 1; i >= 0; i--) { + const currentBrick = bricksRow[i]; + const brickLeft = currentBrick.x; + const brickRight = currentBrick.x + BRICK_WIDTH; + const brickTop = currentBrick.y; + const brickBottom = currentBrick.y + BRICK_HEIGHT; + + const ballLeft = ball.x - BALL_RADIUS; + const ballRight = ball.x + BALL_RADIUS; + const ballTop = ball.y - BALL_RADIUS; + const ballBottom = ball.y + BALL_RADIUS; + + const isCollided = calculateCollision( + { left: ballLeft, right: ballRight, top: ballTop, bottom: ballBottom }, + { left: brickLeft, right: brickRight, top: brickTop, bottom: brickBottom }, + ); + + if (isCollided) { + verticalSpeed *= -1; + } + } + + // Не даем мячу выйти за границы стен слева / справав и меняем направление if (ball.x <= leftBoundary || ball.x >= rightBoundary) { ball.x = ball.x <= leftBoundary ? leftBoundary : rightBoundary; horizontalSpeed *= -1; } - // Не даем выйти за границы стен сверху / снизу и меняем направление + // Не даем мячу выйти за границы стен сверху / снизу и меняем направление if (ball.y <= topBoundary || ball.y >= bottomBoundary) { ball.y = ball.y <= topBoundary ? topBoundary : bottomBoundary; verticalSpeed *= -1;