tennis-game/internal/ball.go
2023-11-29 06:59:38 +00:00

83 lines
1.7 KiB
Go

package internal
import (
"image"
"image/color"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/vector"
)
type ball struct {
x float32
speedX float32
y float32
speedY float32
r float32
}
const (
ballBaseRadius = 5
ballBaseSpeedX = 1
ballBaseSpeedY = 1
)
func newBall(screenWidth, screenHeight int) *ball {
fScreenWidth := float32(screenWidth)
fScreenHeight := float32(screenHeight)
r := ballBaseRadius * fScreenHeight / BaseHeight
return &ball{
x: fScreenWidth/2.0 - r,
speedX: ballBaseSpeedX * fScreenWidth / BaseWidth,
y: fScreenHeight/2.0 - r,
speedY: ballBaseSpeedY * fScreenHeight / BaseHeight,
r: r,
}
}
var ballColor = color.White
func (b *ball) draw(img *ebiten.Image) {
vector.DrawFilledCircle(img, b.x, b.y, b.r, ballColor, false)
}
func (b *ball) update(bounds image.Rectangle) error {
b.x, b.y, b.speedX, b.speedY = b.nextPosAndSpeed(bounds)
return nil
}
//nolint:nonamedreturns
func (b *ball) nextPos(bounds image.Rectangle) (x, y float32) {
x, y, _, _ = b.nextPosAndSpeed(bounds)
return x, y
}
//nolint:nonamedreturns
func (b *ball) nextPosAndSpeed(bounds image.Rectangle) (x, y, speedX, speedY float32) {
speedX, speedY = b.nextSpeed(bounds)
return b.x + speedX, b.y + speedY, speedX, speedY
}
//nolint:nonamedreturns
func (b *ball) nextSpeed(bounds image.Rectangle) (speedX, speedY float32) {
speedX = b.speedX
if b.x+b.r >= float32(bounds.Max.X) || b.x-b.r <= float32(bounds.Min.X) {
speedX *= -1
}
speedY = b.speedY
if b.y+b.r >= float32(bounds.Max.Y) || b.y-b.r <= float32(bounds.Min.Y) {
speedY *= -1
}
return speedX, speedY
}
func (b *ball) resize(x, y float32) {
b.x *= x
b.speedX *= x
b.y *= y
b.speedY *= y
b.r *= y
}