diff options
Diffstat (limited to 'src/game/utils.ts')
-rw-r--r-- | src/game/utils.ts | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/src/game/utils.ts b/src/game/utils.ts new file mode 100644 index 0000000..ec81419 --- /dev/null +++ b/src/game/utils.ts @@ -0,0 +1,24 @@ +import { Ball } from "../state"; +import { VELOCITY_SCALING_FACTOR } from "./const"; + +export const applyBallVelocity = (ball: Ball): Ball => { + let newPos = ball.position.map( + (a, i) => a + ball.velocity[i] * VELOCITY_SCALING_FACTOR + ) as [number, number]; + return { ...ball, position: newPos }; +}; + +export const applyBallBounce = (ball: Ball, normal: [number, number]): Ball => { + //calculate reflection + const newVelocity = ball.velocity.map( + (v, i) => v - v * Math.abs(normal[i]) * 2 + ) as [number, number]; + + //move the ball out of the collider + const newPos = ball.position.map((p, i) => p + normal[i]) as [number, number]; + + //this gives a little punch + let newBall = { velocity: newVelocity, position: newPos }; + newBall = applyBallVelocity(newBall); + return newBall; +}; |