Skip to content

Commit

Permalink
Add BallToPaddleCollision.collisionPoint (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
devfacet authored Mar 21, 2024
1 parent 35c6e25 commit 19eb798
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
15 changes: 11 additions & 4 deletions app/lib/collision.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,17 @@ export class CollisionManager {
collision.playerSide = ball.getPlayerSide()
collision.paddlePlayerSide = paddle.getPlayerSide()

// Calculate the angle of the collision
let collidePoint = ball.getY() - (paddle.getY() + paddle.getHeight() / 2)
collidePoint = collidePoint / (paddle.getHeight() / 2)
// Calculate the collision point
collision.collisionPoint = ball.getY() - paddle.getY()

// Calculate the normalized collision point for determining the angle
// If it's a negative number, the ball is hitting the top half of the paddle.
// If it's a positive number, the ball is hitting the bottom half of the paddle.
// -1 represents the top edge of the paddle, 1 represents the bottom edge of the paddle
let collisionPoint = ball.getY() - (paddle.getY() + paddle.getHeight() / 2)
collisionPoint = collisionPoint / (paddle.getHeight() / 2)
// Convert the angle to radians
const angleRad = (Math.PI / 3) * collidePoint
const angleRad = (Math.PI / 3) * collisionPoint
// Calculate the magnitude of the current velocity
const magnitude = Math.sqrt(ball.getSpeedX() * ball.getSpeedX() + ball.getSpeedY() * ball.getSpeedY())

Expand Down Expand Up @@ -311,6 +317,7 @@ export type BallToPaddleCollision = {
futureY?: number
playerSide?: PlayerSide
paddlePlayerSide?: PlayerSide
collisionPoint?: number
}

// BallToBallCollision represents a collision between two balls.
Expand Down
2 changes: 1 addition & 1 deletion app/lib/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ export class Game {

// onBallToPaddleCollision handles the ball to paddle collision.
private onBallToPaddleCollision = (collision: BallToPaddleCollision): void => {
this.wsSend(`{"event": "collision", "collision": {"kind": "ballToPaddle", "playerSide": "${collision.playerSide}", "paddlePlayerSide": "${collision.paddlePlayerSide}"}}`)
this.wsSend(`{"event": "collision", "collision": {"kind": "ballToPaddle", "playerSide": "${collision.playerSide}", "paddlePlayerSide": "${collision.paddlePlayerSide}", "collisionPoint": ${collision.collisionPoint || 0}}}`)
}

// onBallToGridCollision handles the ball to grid collision.
Expand Down

0 comments on commit 19eb798

Please sign in to comment.