generated from sionleroux/ebitengine-game-template
-
Notifications
You must be signed in to change notification settings - Fork 3
/
dog.go
498 lines (442 loc) · 13.7 KB
/
dog.go
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
// Use of this source code is subject to an MIT-style
// licence which can be found in the LICENSE file.
package main
import (
"image"
"math"
"github.com/hajimehoshi/ebiten/v2"
"github.com/solarlune/resolv"
)
// Coord is the coordinate of a path point
type Coord struct {
X float64
Y float64
}
// Path contains information about a path and its progress
type Path struct {
Points []Coord // Coordinates of the path points
NextPoint int // Index of the next path point
}
// dogWalkingSpeed is the distance the dog moves per update cycle when walking
var dogWalkingSpeed float64 = 0.7
// dogRunningSpeed is the distance the dog moves per update cycle when running
var dogRunningSpeed float64 = 1.3
// waitingRadius is the maximum distance the dog walks away from the player
var waitingRadius float64 = 96
// followingRadius is the distance within which the dog follows the player after the last checkpoint
var followingRadius float64 = 96
// zombieBarkRadius: if a zombie is this close to the dog, it barks
var zombieBarkRadius float64 = 150
// zombieFleeRadius: if a zombie is this close to the dog, it runs away
var zombieFleeRadius float64 = 80
// zombieSafeRadius: if a zombie is at least this far from the dog, it stops running
var zombieSafeRadius float64 = 192
// fleeingPathLength: the length of the path planned for fleeing
var fleeingPathLength float64 = 200
// how much time (ticks) the dog can be out of sight before it dies
var outOfSightLimit int = 300
// Operating modes of the dog
const (
dogNormal = iota // Dog is alive and no zombies in vicinity
dogDanger // Zomibes are close, the dod needs to flee
dogDead // Dog died
)
// States of the dog
const (
dogNormalWaiting = iota
dogNormalWalking
dogNormalBlocked
dogNormalSniffing
dogNormalWaitingAtCheckpoint
dogDangerBarking
dogDangerFleeing
)
// Maps dog states to animation frames
var dogStateToFrame = [7]int{2, 0, 2, 1, 2, 1, 0}
// Dog is player's companion
type Dog struct {
Object *resolv.Object
Angle float64
TempSpeed float64
Frame int
Mode int
State int
PrevState int
CurrentPath *Path
MainPath *Path
OnMainPath bool
LastPathCoord Coord
Sprite *SpriteSheet
PrevCheckpoint int
LastPathpointReached bool
AtCheckpointCounter int
OutOfSightCounter int
}
func (d *Dog) Init() {
d.TempSpeed = 1
d.CurrentPath = d.MainPath
d.OnMainPath = true
d.turnTowardsPathPoint()
}
// Resets the dog to a coordinate after death
func (d *Dog) Reset(cp int, x, y float64) {
d.OutOfSightCounter = 0
d.Mode = dogNormal
d.State = dogNormalWaiting
d.CurrentPath = d.MainPath
d.CurrentPath.NextPoint = d.findClosestPathPoint(x, y)
d.OnMainPath = true
d.Object.Position.X, d.Object.Position.Y = x, y
d.turnTowardsPathPoint()
}
// Finds the closest pathpoint on the dog's path
func (d *Dog) findClosestPathPoint(x, y float64) int {
minDest := 1000.0
index := 0
for i, p := range d.MainPath.Points {
d := CalcDistance(x, y, p.X, p.Y)
if d < minDest {
minDest = d
index = i
}
}
return index
}
// zombiesInRange checks if there zombies close to the Dog
// Returns
// - if there are zombies in range
// - the distance of the closest zombie
// - the resultant vector of the fleeing path based on all the zombies in range
func (d *Dog) zombiesInRange(zRange float64, g *GameScreen) (bool, float64, Coord) {
resultantVectorCoord := Coord{X: 0, Y: 0}
closestZombie := 1000.0
for _, zombie := range g.Zombies {
zombieDistance, xDistance, yDistance := CalcObjectDistance(d.Position(), zombie.Position())
if zombieDistance < closestZombie {
closestZombie = zombieDistance
}
if zombieDistance < zRange {
resultantVectorCoord.X += xDistance
resultantVectorCoord.Y += yDistance
}
}
return closestZombie < zRange, closestZombie, resultantVectorCoord
}
// planFleeingRoute plans a fleeing route for the dog
func (d *Dog) planFleeingRoute(vector Coord, g *GameScreen) *Path {
fleeingPath := &Path{}
nv := NormalizeVector(vector)
fleeingPath.Points = []Coord{
{X: d.Object.Position.X + nv.X*fleeingPathLength, Y: d.Object.Position.Y + nv.Y*fleeingPathLength},
}
return fleeingPath
}
// planRouteBackToMainPath plans a route back to the main path
func (d *Dog) planRouteBackToMainPath(g *GameScreen) *Path {
returnPath := &Path{}
returnPath.Points = g.LevelMap.FindPath(
Coord{X: d.Object.Position.X, Y: d.Object.Position.Y},
d.LastPathCoord,
)
returnPath.Points[len(returnPath.Points)-1] = d.LastPathCoord
returnPath.Points = GetBezierPathFromCoords(returnPath.Points, 2)
return returnPath
}
// updateState updates the state machine of the dog
func (d *Dog) updateState(g *GameScreen) {
d.PrevState = d.State
// Does the dog need to change mode? Danger <-> Normal
switch d.Mode {
case dogNormal:
zInRange, _, _ := d.zombiesInRange(zombieBarkRadius, g)
if zInRange {
d.Mode = dogDanger
d.State = dogDangerBarking
}
case dogDanger:
zInRange, _, _ := d.zombiesInRange(zombieSafeRadius, g)
if !zInRange {
d.Mode = dogNormal
d.State = dogNormalWaiting
}
}
// Does the dog need to change state in its current mode?
switch d.Mode {
case dogNormal:
playerDistance, _, _ := CalcObjectDistance(d.Position(), g.Player.Position())
switch d.State {
case dogNormalWaiting:
if d.PrevState == dogDangerFleeing {
d.CurrentPath = d.planRouteBackToMainPath(g)
d.turnTowardsPathPoint()
d.OnMainPath = false
}
if playerDistance <= waitingRadius {
d.State = dogNormalWalking
}
case dogNormalWalking:
if playerDistance > waitingRadius {
d.State = dogNormalWaiting
}
// Next state is set elsewhere
// - In case when dog reaches checkpoint and starts sniffing
// - In case when dog reaches destination
// - In case when dog is getting blocked by the player
case dogNormalBlocked:
// Next state is set elsewhere
// - In case when dog is not blocked anymore by the player
case dogNormalSniffing:
// If the player has already touched the checkpoint previously
if d.PrevCheckpoint == g.Checkpoint {
d.State = dogNormalWalking
}
// Sniffing for 3 seconds
if d.AtCheckpointCounter >= 180 {
d.State = dogNormalWaitingAtCheckpoint
}
// Next state is set elsewhere
// - In case when player is also at the checkpoint
case dogNormalWaitingAtCheckpoint:
// Next state is set elsewhere
// - In case when player is also at the checkpoint
}
case dogDanger:
zInRange, _, _ := d.zombiesInRange(zombieFleeRadius, g)
switch d.State {
case dogDangerBarking:
if zInRange {
if d.OnMainPath {
d.LastPathCoord = d.CurrentPath.Points[d.CurrentPath.NextPoint]
}
d.State = dogDangerFleeing
}
case dogDangerFleeing:
// Dog is fleeing until it changes mode to Normal
}
}
}
// Update updates the state of the dog
func (d *Dog) Update(g *GameScreen) {
// If the dog is dead, no need to update
if d.Mode == dogDead {
return
}
d.updateState(g)
// If the dog is out of the screen for too long then it dies
sx, sy := g.Camera.GetScreenCoords(d.Object.Position.X, d.Object.Position.Y)
if sx < 0 || sy < 0 || sx > float64(g.Width) || sy > float64(g.Height) {
d.OutOfSightCounter++
if d.OutOfSightCounter > outOfSightLimit {
g.Dog.Mode = dogDead
}
} else {
d.OutOfSightCounter = 0
}
// Update dog based on current and previous states
switch d.State {
case dogNormalWaiting:
// Do nothing
case dogNormalWalking:
// If dog is walking back to the main path and reaches it then change its path to main path
// Try to move along the path
d.walk(g)
case dogNormalBlocked:
// Try to move along the path
d.walk(g)
case dogNormalSniffing:
d.AtCheckpointCounter++
// Wait for the player to arrive at the same checkpoint
case dogNormalWaitingAtCheckpoint:
d.AtCheckpointCounter++
// Dog barks at every 5 seconds
if d.AtCheckpointCounter%300 == 0 {
g.Sounds[soundDogBark].Play()
}
// Wait for the player to arrive at the same checkpoint
case dogDangerBarking:
// Play barking sound
if d.PrevState != dogDangerBarking {
g.Sounds[soundDogBark].Play()
}
case dogDangerFleeing:
zInRange, _, resultantVector := d.zombiesInRange(zombieFleeRadius, g)
if zInRange {
d.CurrentPath = d.planFleeingRoute(resultantVector, g)
d.turnTowardsPathPoint()
d.OnMainPath = false
}
// Try to run along the path
d.followPath(g)
}
// If dog is walking then after some time a flavour voice line is played
if d.State == dogNormalWalking || d.State == dogNormalBlocked {
if g.Checkpoint > 0 && g.Checkpoint < 7 {
if (g.NextVoiceStep == voiceStepFlavour1 || g.NextVoiceStep == voiceStepFlavour2) && g.VoiceGuardTime > voiceGuardTime {
i := 0
if g.NextVoiceStep == voiceStepFlavour2 {
i = 1
}
g.Voices[voiceFlavour].PlayVariant((g.Checkpoint-1)*2 + i)
g.VoiceGuardTime = 0
g.NextVoiceStep++
}
}
}
// Animate dog
animationFrame := d.Sprite.Meta.FrameTags[dogStateToFrame[d.State]]
d.Frame = Animate(d.Frame, g.Tick, animationFrame)
d.Object.Update()
}
// ContinueFromCheckpoint continues walking on the path when the player is at the same checkpoint
// If the last checkpoint is reached then the dog starts following the player
func (d *Dog) ContinueFromCheckpoint() {
d.State = dogNormalWalking
}
// walk moves the dog either on a path or by following the player
func (d *Dog) walk(g *GameScreen) {
if d.LastPathpointReached {
d.followPlayer(g)
} else {
d.followPath(g)
}
}
// TurnTowardsCoordinate turns the dog to the direction of the point
func (d *Dog) turnTowardsCoordinate(coord Coord) {
adjacent := coord.X - d.Object.Position.X
opposite := coord.Y - d.Object.Position.Y
d.Angle = math.Atan2(opposite, adjacent)
}
// TurnTowardsPathPoint turns the dog to the direction of the next path point
func (d *Dog) turnTowardsPathPoint() {
d.turnTowardsCoordinate(d.CurrentPath.Points[d.CurrentPath.NextPoint])
}
func (d *Dog) followPlayer(g *GameScreen) {
d.turnTowardsCoordinate(Coord{X: g.Player.Object.Position.X, Y: g.Player.Object.Position.Y})
d.move(
math.Cos(d.Angle)*dogWalkingSpeed*d.TempSpeed,
math.Sin(d.Angle)*dogWalkingSpeed*d.TempSpeed,
)
}
// followPath moves the dog along its current path
func (d *Dog) followPath(g *GameScreen) {
if d.CurrentPath.NextPoint == len(d.CurrentPath.Points) {
return
}
nextPoint := d.CurrentPath.Points[d.CurrentPath.NextPoint]
nextPathCoordDistance := CalcDistance(nextPoint.X, nextPoint.Y, d.Object.Position.X, d.Object.Position.Y)
if nextPathCoordDistance < 2 {
d.CurrentPath.NextPoint++
if d.CurrentPath.NextPoint == len(d.CurrentPath.Points) {
if d.State == dogNormalWalking {
// If the dog is normally walking, not fleeing
if d.OnMainPath {
// If the dog reaches the end of the main path then it finishes
d.LastPathpointReached = true
return
} else {
// If the dog reaches the main path again then it will continue on that
d.CurrentPath = d.MainPath
d.OnMainPath = true
}
} else {
// If the dog is fleeing
zInRange, _, resultantVector := d.zombiesInRange(zombieFleeRadius, g)
if !zInRange {
return
}
d.CurrentPath = d.planFleeingRoute(resultantVector, g)
}
}
d.turnTowardsPathPoint()
return
}
var speed float64
if d.State == dogDangerFleeing {
speed = dogRunningSpeed
} else {
speed = dogWalkingSpeed
}
d.move(
math.Cos(d.Angle)*speed*d.TempSpeed,
math.Sin(d.Angle)*speed*d.TempSpeed,
)
}
// Move the Dog by the given vector if it is possible to do so
func (d *Dog) move(dx, dy float64) {
// Collision detection and response between sand trap and dog
d.TempSpeed = 1
if collision := d.Object.Check(0, 0, tagSandTrap); collision != nil {
if d.Object.Shape.Intersection(0, 0, collision.Objects[0].Shape) != nil {
d.TempSpeed = sandTrapSpeedMultiplier
}
}
switch d.State {
case dogNormalWalking:
// If the dog would collide with the player
if collision := d.Object.Check(dx, dy, tagPlayer); collision != nil {
if d.Object.Shape.Intersection(0, 0, collision.Objects[0].Shape) != nil {
d.State = dogNormalBlocked
return
}
}
// If the dog reaches a checkpoint
if collision := d.Object.Check(dx, dy, tagCheckpoint); collision != nil {
o := collision.Objects[0]
// If the dog or the player has not been at the checkpoint before
if o.Data.(int) > d.PrevCheckpoint {
d.PrevCheckpoint = o.Data.(int)
}
d.AtCheckpointCounter = 0
d.State = dogNormalSniffing
}
case dogNormalBlocked:
// If the dog would not collide with the player anymore
if collision := d.Object.Check(dx, dy, tagPlayer); collision == nil {
d.State = dogNormalWalking
} else {
return
}
default:
if collision := d.Object.Check(dx, dy, tagWall, tagMob, tagPlayer); collision != nil {
if d.Object.Shape.Intersection(0, 0, collision.Objects[0].Shape) != nil {
return
}
}
}
d.Object.Position.X += dx
d.Object.Position.Y += dy
}
// Draw draws the Dog to the screen
func (d *Dog) Draw(g *GameScreen) {
// the centre of the dog's shoulders is 5px down from the middle
const centerOffset float64 = 5
s := d.Sprite
frame := s.Sprite[d.Frame]
op := &ebiten.DrawImageOptions{}
// Centre and rotate
op.GeoM.Translate(
float64(-frame.Position.W/2),
float64(-frame.Position.H/2)+centerOffset/2,
)
op.GeoM.Rotate(d.Angle + math.Pi/2)
g.Camera.Surface.DrawImage(
s.Image.SubImage(image.Rect(
frame.Position.X,
frame.Position.Y,
frame.Position.X+frame.Position.W,
frame.Position.Y+frame.Position.H,
)).(*ebiten.Image),
g.Camera.GetTranslation(
op,
float64(d.Object.Position.X),
float64(d.Object.Position.Y),
),
)
}
// Position returns the Dog's current coordinates
func (d *Dog) Position() *Coord {
return &Coord{
X: d.Object.Position.X,
Y: d.Object.Position.Y,
}
}