ball now bounces on window edges

This commit is contained in:
sigmasternchen 2024-11-01 18:48:20 +01:00
parent 687cb1b034
commit 1a0589cb26
2 changed files with 31 additions and 9 deletions

View file

@ -4,7 +4,7 @@ import {choice} from "../utils";
import {defaultBallSpeed, startAngles} from "./parameters"; import {defaultBallSpeed, startAngles} from "./parameters";
export class Ball { export class Ball {
private _position: Position; public position: Position;
private phi: number; private phi: number;
private speed: number; private speed: number;
private readonly element: HTMLElement; private readonly element: HTMLElement;
@ -20,13 +20,10 @@ export class Ball {
this.redraw(); this.redraw();
} }
set position(position: Position) {
this._position = position;
}
public readonly redraw = (): void => { public readonly redraw = (): void => {
this.element.style.left = this._position.x + "px"; console.log(this.phi / Math.PI, this.position.x, this.position.y);
this.element.style.top = this._position.y + "px"; this.element.style.left = this.position.x + "px";
this.element.style.top = this.position.y + "px";
} }
public readonly setup = (gameElement: HTMLElement): void => { public readonly setup = (gameElement: HTMLElement): void => {
@ -39,7 +36,12 @@ export class Ball {
} }
public readonly tick = (delta: number): void => { 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(); 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;
}
} }

View file

@ -46,9 +46,29 @@ export class Game {
const delta = timestamp - this.lastTickTimestamp; const delta = timestamp - this.lastTickTimestamp;
this.lastTickTimestamp = timestamp; this.lastTickTimestamp = timestamp;
this.balls.forEach(ball => ball.tick(delta)); this.balls.forEach(ball => {
ball.tick(delta);
this.handleCollisions(ball);
});
if (this.running) { if (this.running) {
requestAnimationFrame(this.tick); 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);
}
}
} }