collision detection woo

This commit is contained in:
Josh Deprez 2021-08-03 14:56:53 +10:00 committed by Josh Deprez
parent eada25274d
commit 9c456296b9
2 changed files with 50 additions and 7 deletions

View file

@ -1,19 +1,46 @@
package engine package engine
import "math" import (
"encoding/gob"
"image"
"math"
)
func init() {
gob.Register(Actor{})
}
// Thorson-style movement: // Thorson-style movement:
// https://maddythorson.medium.com/celeste-and-towerfall-physics-d24bd2ae0fc5 // https://maddythorson.medium.com/celeste-and-towerfall-physics-d24bd2ae0fc5
const collide = false // TODO: add collision detection // Collider components have tangible form.
type Collider interface {
CollidesWith(image.Rectangle) bool
}
type Actor struct { type Actor struct {
X, Y int Position image.Point
Size image.Point
game *Game game *Game
xRem, yRem float64 xRem, yRem float64
} }
func (a *Actor) collidesAt(p image.Point) bool {
// TODO: more efficient test?
hit := false
a.game.Walk(func(c interface{}) bool {
if coll, ok := c.(Collider); ok {
if coll.CollidesWith(image.Rectangle{Min: p, Max: p.Add(a.Size)}) {
hit = true
return false
}
}
return true
})
return hit
}
func (a *Actor) MoveX(dx float64, onCollide func()) { func (a *Actor) MoveX(dx float64, onCollide func()) {
a.xRem += dx a.xRem += dx
move := int(math.Round(a.xRem)) move := int(math.Round(a.xRem))
@ -23,13 +50,13 @@ func (a *Actor) MoveX(dx float64, onCollide func()) {
a.xRem -= float64(move) a.xRem -= float64(move)
sign := sign(move) sign := sign(move)
for move != 0 { for move != 0 {
if collide { if a.collidesAt(a.Position.Add(image.Pt(sign, 0))) {
if onCollide != nil { if onCollide != nil {
onCollide() onCollide()
} }
return return
} }
a.X += sign a.Position.X += sign
move -= sign move -= sign
} }
} }
@ -43,13 +70,13 @@ func (a *Actor) MoveY(dy float64, onCollide func()) {
a.yRem -= float64(move) a.yRem -= float64(move)
sign := sign(move) sign := sign(move)
for move != 0 { for move != 0 {
if collide { if a.collidesAt(a.Position.Add(image.Pt(0, sign))) {
if onCollide != nil { if onCollide != nil {
onCollide() onCollide()
} }
return return
} }
a.Y += sign a.Position.Y += sign
move -= sign move -= sign
} }
} }

16
engine/solid.go Normal file
View file

@ -0,0 +1,16 @@
package engine
import (
"encoding/gob"
"image"
)
func init() {
gob.Register(SolidRect{})
}
type SolidRect struct {
Rect image.Rectangle
}
func (s SolidRect) CollidesWith(r image.Rectangle) bool { return s.Rect.Overlaps(r) }