diff --git a/src/game/Ball.ts b/src/game/Ball.ts index 93e9a4e..e8651e1 100644 --- a/src/game/Ball.ts +++ b/src/game/Ball.ts @@ -4,7 +4,7 @@ import {choice} from "../utils"; import {defaultBallSpeed, startAngles} from "./parameters"; export class Ball { - private _position: Position; + public position: Position; private phi: number; private speed: number; private readonly element: HTMLElement; @@ -20,13 +20,10 @@ export class Ball { this.redraw(); } - set position(position: Position) { - this._position = position; - } - public readonly redraw = (): void => { - this.element.style.left = this._position.x + "px"; - this.element.style.top = this._position.y + "px"; + 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"; } public readonly setup = (gameElement: HTMLElement): void => { @@ -39,7 +36,12 @@ export class Ball { } public readonly tick = (delta: number): void => { - this._position = this._position.moveInDirection(this.phi, this.speed * delta / 1000); + this.position = this.position.moveInDirection(this.phi, this.speed * delta / 1000); this.redraw(); } + + public readonly collision = (wallAngle: number): void => { + this.phi = 2 * wallAngle - this.phi; + this.phi -= (0|(this.phi / (Math.PI*2))) * Math.PI * 2; + } } \ No newline at end of file diff --git a/src/game/Game.ts b/src/game/Game.ts index 004a031..986354c 100644 --- a/src/game/Game.ts +++ b/src/game/Game.ts @@ -46,9 +46,29 @@ export class Game { const delta = timestamp - this.lastTickTimestamp; this.lastTickTimestamp = timestamp; - this.balls.forEach(ball => ball.tick(delta)); + this.balls.forEach(ball => { + ball.tick(delta); + this.handleCollisions(ball); + }); + if (this.running) { requestAnimationFrame(this.tick); } } + + private readonly handleCollisions = (ball: Ball): void => { + this.handleEdgeCollisions(ball); + } + + private readonly handleEdgeCollisions = (ball: Ball): void => { + if (ball.position.x < 0) { + ball.collision(Math.PI / 2); + } else if (ball.position.x >= fieldWidth) { + ball.collision(Math.PI / 2); + } else if (ball.position.y < 0) { + ball.collision(0); + } else if (ball.position.y >= fieldHeight) { + ball.collision(0); + } + } }