mirror of
https://github.com/sigmasternchen/88x31breakout
synced 2025-03-15 07:59:00 +00:00
ball now bounces on window edges
This commit is contained in:
parent
687cb1b034
commit
1a0589cb26
2 changed files with 31 additions and 9 deletions
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue