From 0573a60c295c171ea175cdd244c340927fd7a4c2 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Sun, 2 Mar 2025 18:45:07 +0100 Subject: [PATCH] add ball --- ball.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 35 ++++------------------------------- 2 files changed, 52 insertions(+), 31 deletions(-) create mode 100644 ball.go diff --git a/ball.go b/ball.go new file mode 100644 index 0000000..365ef46 --- /dev/null +++ b/ball.go @@ -0,0 +1,48 @@ +package main + +import "math/rand" + +const ( + ballSize = 8 + ballSpeed = 3 + ballStartY = screenHeight - 60 +) + +type ball struct { + x, y, dx, dy, size float32 +} + +func newBall() ball { + return ball{ + x: screenWidth / 2, + y: ballStartY, + dx: ballSpeed, + dy: -ballSpeed, + size: ballSize, + } +} + +func (b *ball) updatePosition() { + b.x += b.dx + b.y += b.dy +} + +func (b *ball) checkWallCollision() { + if b.x <= 0 || b.x >= screenWidth-b.size { + b.dx = -b.dx + } + if b.y <= 0 { + b.dy = -b.dy + } +} + +func (b *ball) checkPaddleCollision(p paddle) { + if b.y+b.size >= p.y && + b.x+b.size >= p.x && + b.x <= p.x+p.width && + b.y <= p.y+p.height { + b.dy = -b.dy + // Add some randomness to the ball direction + b.dx += (rand.Float32()*2 - 1) * 0.5 + } +} diff --git a/main.go b/main.go index 6652198..702439e 100644 --- a/main.go +++ b/main.go @@ -3,7 +3,6 @@ package main import ( "image/color" "log" - "math/rand" "strconv" "github.com/hajimehoshi/ebiten/v2" @@ -13,9 +12,6 @@ import ( const ( screenWidth = 640 screenHeight = 480 - ballSize = 8 - ballSpeed = 3 - ballStartY = screenHeight - 60 ) type Game struct { @@ -27,22 +23,12 @@ type Game struct { initialized bool } -type ball struct { - x, y, dx, dy, size float64 -} - func (g *Game) init() { // Initialize paddle g.paddle = newPaddle() // Initialize ball - g.ball = ball{ - x: screenWidth / 2, - y: ballStartY, - dx: ballSpeed, - dy: -ballSpeed, - size: ballSize, - } + g.ball = newBall() // Initialize bricks g.bricks = initBricks() @@ -75,26 +61,13 @@ func (g *Game) Update() error { g.paddle.keepWithinBounds() // Update ball position - g.ball.x += g.ball.dx - g.ball.y += g.ball.dy + g.ball.updatePosition() // Ball collision with walls - if g.ball.x <= 0 || g.ball.x >= screenWidth-g.ball.size { - g.ball.dx = -g.ball.dx - } - if g.ball.y <= 0 { - g.ball.dy = -g.ball.dy - } + g.ball.checkWallCollision() // Ball collision with paddle - if g.ball.y+g.ball.size >= g.paddle.y && - g.ball.x+g.ball.size >= g.paddle.x && - g.ball.x <= g.paddle.x+g.paddle.width && - g.ball.y <= g.paddle.y+g.paddle.height { - g.ball.dy = -g.ball.dy - // Add some randomness to the ball direction - g.ball.dx += (rand.Float64()*2 - 1) * 0.5 - } + g.ball.checkPaddleCollision(g.paddle) // Ball collision with bricks for i := range g.bricks {