tennis-game/internal/ball.go
2023-11-28 05:52:00 +00:00

66 lines
1.2 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 (
ballBaselRadius = 5
ballBaseSpeedX = 1
ballBaseSpeedY = 1
)
func newBall(screenWidth, screenHeight int) *ball {
fScreenWidth := float32(screenWidth)
fScreenHeight := float32(screenHeight)
r := ballBaselRadius * 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 {
if b.x+b.r >= float32(bounds.Max.X) || b.x-b.r <= float32(bounds.Min.X) {
b.speedX *= -1
}
if b.y+b.r >= float32(bounds.Max.Y) || b.y-b.r <= float32(bounds.Min.Y) {
b.speedY *= -1
}
b.x += b.speedX
b.y += b.speedY
return nil
}
func (b *ball) resize(x, y float32) {
b.x *= x
b.speedX *= x
b.y *= y
b.speedY *= y
b.r *= y
}