summaryrefslogtreecommitdiff
path: root/engine/CoreObjects/Collider.go
blob: 8e9f47291f515d6cc3ec0864974ea835e4cf7db1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package coreobjects

import (
	"image/color"

	settings "github.com/DegustatorPonos/RuinesOfRafdolon/Settings"
	rl "github.com/gen2brain/raylib-go/raylib"
)

var ColliderColour color.RGBA = color.RGBA{ 154, 20, 184, 255 / 2 }

type Collider interface {
	Init(x float32, y float32, height float32, width float32) Collider
	MoveIfPossible(colliders []*Collider, dx float32, dy float32)
	Move(dx float32, dy float32)
	MoveTo(x float32, y float32)
	Intersects(x float32, y float32) bool
	CanMove(colliders []*Collider, dx float32, dy float32) bool
	Clone() Collider

	Draw()
}

type BoxCollider struct {
	Location rl.Rectangle
}

func (base *BoxCollider) Init(x float32, y float32, height float32, width float32) Collider { 
	base.Location = rl.Rectangle{
		X: x,
		Y: y,
		Width: width,
		Height: height,
	}
	return base
}

func (base *BoxCollider) Intersects(x float32, y float32) bool {
	return rl.CheckCollisionPointRec(rl.Vector2 { X: x, Y: y }, base.Location)
}

func (base *BoxCollider) Move(dx float32, dy float32) {
	base.Location.X += dx
	base.Location.Y += dy
}

func (base *BoxCollider) MoveTo(x float32, y float32) {
	base.Location.X = x
	base.Location.Y = y
}

func (base *BoxCollider) MoveIfPossible(colliders []*Collider, dx float32, dy float32) {
	if base.CanMove(colliders, dx, dy) {
		base.Move(dx, dy)
	}
}

func (base *BoxCollider) Draw() {
	if !settings.State.DrawColliders {
		return
	}
	rl.DrawRectangle(base.Location.ToInt32().X, 
		base.Location.ToInt32().Y,
		base.Location.ToInt32().Width, 
		base.Location.ToInt32().Height,
		ColliderColour)
}

func (base *BoxCollider) CanMove(colliders []*Collider, dx float32, dy float32) bool {
	var x = base.Location.X + dx
	var y = base.Location.Y + dy
	var width = base.Location.Width
	var height = base.Location.Height
	
	// TODO: optimise
	for _, v := range colliders {
		if  (*v).Intersects(x, y) ||
			(*v).Intersects(x + width, y) ||
			(*v).Intersects(x, y + height) ||
			(*v).Intersects(x + width, y + height) {
				return false
			}
	}
	return true
}

func (base *BoxCollider) Clone() Collider {
	var clone = (&BoxCollider{}).Init (
		base.Location.X, base.Location.Y,
		base.Location.Width, base.Location.Height)
	return clone
}