collision detection woo
This commit is contained in:
parent
eada25274d
commit
9c456296b9
2 changed files with 50 additions and 7 deletions
|
@ -1,19 +1,46 @@
|
|||
package engine
|
||||
|
||||
import "math"
|
||||
import (
|
||||
"encoding/gob"
|
||||
"image"
|
||||
"math"
|
||||
)
|
||||
|
||||
func init() {
|
||||
gob.Register(Actor{})
|
||||
}
|
||||
|
||||
// Thorson-style movement:
|
||||
// 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 {
|
||||
X, Y int
|
||||
Position image.Point
|
||||
Size image.Point
|
||||
|
||||
game *Game
|
||||
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()) {
|
||||
a.xRem += dx
|
||||
move := int(math.Round(a.xRem))
|
||||
|
@ -23,13 +50,13 @@ func (a *Actor) MoveX(dx float64, onCollide func()) {
|
|||
a.xRem -= float64(move)
|
||||
sign := sign(move)
|
||||
for move != 0 {
|
||||
if collide {
|
||||
if a.collidesAt(a.Position.Add(image.Pt(sign, 0))) {
|
||||
if onCollide != nil {
|
||||
onCollide()
|
||||
}
|
||||
return
|
||||
}
|
||||
a.X += sign
|
||||
a.Position.X += sign
|
||||
move -= sign
|
||||
}
|
||||
}
|
||||
|
@ -43,13 +70,13 @@ func (a *Actor) MoveY(dy float64, onCollide func()) {
|
|||
a.yRem -= float64(move)
|
||||
sign := sign(move)
|
||||
for move != 0 {
|
||||
if collide {
|
||||
if a.collidesAt(a.Position.Add(image.Pt(0, sign))) {
|
||||
if onCollide != nil {
|
||||
onCollide()
|
||||
}
|
||||
return
|
||||
}
|
||||
a.Y += sign
|
||||
a.Position.Y += sign
|
||||
move -= sign
|
||||
}
|
||||
}
|
||||
|
|
16
engine/solid.go
Normal file
16
engine/solid.go
Normal 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) }
|
Loading…
Reference in a new issue