Slide and collide!

This commit is contained in:
2024-07-18 17:21:25 +08:00
parent b4c2cdccaf
commit 9025859fac
9 changed files with 126 additions and 4 deletions

View File

@@ -8,7 +8,7 @@ type Object interface {
}
type DrawableObject interface {
Draw(*sdl.Renderer)
Draw(pen *sdl.Renderer)
}
type BaseObject struct {

View File

@@ -0,0 +1,18 @@
package land
type CollidableObject interface {
GetPosition() Vector2D
GetSize() Vector2D
OnCollide(other CollidableObject)
}
func checkCollisionBetweenObject(a, b CollidableObject) bool {
aPos := a.GetPosition()
aSize := a.GetSize()
bPos := b.GetPosition()
bSize := b.GetSize()
return aPos.X < bPos.X+bSize.X &&
aPos.X+aSize.X > bPos.X &&
aPos.Y < bPos.Y+bSize.Y &&
aPos.Y+aSize.Y > bPos.Y
}

View File

@@ -0,0 +1,6 @@
package land
type MoveableObject interface {
Move(deltaX int64, deltaY int64)
SlideByVelocity()
}

View File

@@ -19,7 +19,7 @@ func (p *PerformanceAnalyzer) Draw() {
atomic.AddInt64(&p.drawCount, 1)
}
func (p *PerformanceAnalyzer) KeepResetting(duration time.Duration) {
func (p *PerformanceAnalyzer) RunResetter(duration time.Duration) {
ticker := time.NewTicker(duration)
defer ticker.Stop()
for {

View File

@@ -16,7 +16,7 @@ func NewRootObject() *RootObject {
Analyzer: &PerformanceAnalyzer{},
}
go in.Analyzer.KeepResetting(1 * time.Second)
go in.Analyzer.RunResetter(1 * time.Second)
return in
}
@@ -38,6 +38,24 @@ func (p *RootObject) RunEventLoop(tickDuration time.Duration) {
func (p *RootObject) Update() {
p.BaseObject.Update()
// Check collision
for _, child := range p.Children {
for _, other := range p.Children {
collidableChild, ok := child.(CollidableObject)
if !ok {
continue
}
collidableOther, ok := other.(CollidableObject)
if !ok {
continue
}
if child != other && checkCollisionBetweenObject(collidableChild, collidableOther) {
collidableChild.OnCollide(collidableOther)
collidableOther.OnCollide(collidableChild)
}
}
}
p.Analyzer.Tick()
}

View File

@@ -3,3 +3,7 @@ package land
type Vector2D struct {
X, Y float64
}
func (p Vector2D) IsZero() bool {
return p.X == 0 && p.Y == 0
}