feat: Banners now have collisions

This commit is contained in:
sigmasternchen 2024-11-01 19:56:23 +01:00
parent e864112755
commit a43a70f523
3 changed files with 36 additions and 1 deletions

View file

@ -26,7 +26,6 @@ export class Ball {
}
public readonly redraw = (): void => {
console.log(this.phi / Math.PI, this.position.x, this.position.y);
this.element.style.left = this.position.x + "px";
this.element.style.top = this.position.y + "px";
}

View file

@ -2,6 +2,8 @@
import banners from 'banners';
import {toShuffled} from "../utils";
import {Position} from "./Position";
import {Ball} from "./Ball";
import {ballSize} from "./geometry";
export class Banner {
private readonly position: Position;
@ -31,6 +33,35 @@ export class Banner {
public readonly setup = (gameElement: HTMLElement): void => {
gameElement.appendChild(this.element);
}
public readonly remove = (gameElement: HTMLElement): void => {
gameElement.removeChild(this.element);
}
public readonly handleCollisions = (ball: Ball): boolean => {
if (
ball.position.x + ballSize / 2 > this.position.x &&
ball.position.x - ballSize / 2 < this.position.x + 88 &&
ball.position.y + ballSize / 2 > this.position.y &&
ball.position.y - ballSize / 2 < this.position.y + 31
) {
const distancesWithAngles = [
{ distance: Math.abs(ball.position.x - this.position.x), phi: Math.PI / 2 }, // left
{ distance: Math.abs(ball.position.x - this.position.x + 88), phi: Math.PI /2 }, // right
{ distance: Math.abs(ball.position.y - this.position.y), phi: 0 }, // top
{ distance: Math.abs(ball.position.y - this.position.y + 31), phi: 0 }, // bottom
];
console.log(distancesWithAngles);
const closestAngle = distancesWithAngles.sort((a, b) => a.distance - b.distance)[0];
ball.collision(closestAngle.phi);
return true;
} else {
return false;
}
}
}
export const makeBanners = (numberOfBanners: number, positioning: (i: number) => Position) =>

View file

@ -59,6 +59,11 @@ export class Game {
private readonly handleCollisions = (ball: Ball): void => {
this.handleEdgeCollisions(ball);
this.paddle.handleCollisions(ball);
const toDelete = this.banners.filter(banner => banner.handleCollisions(ball));
toDelete.forEach(banner => banner.remove(this.root));
this.banners = this.banners.filter(banner => !toDelete.includes(banner));
}
private readonly handleEdgeCollisions = (ball: Ball): void => {