generated from sionleroux/ebitengine-game-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cursor.go
116 lines (101 loc) · 2.3 KB
/
cursor.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
// Copyright 2022 Siôn le Roux. All rights reserved.
// Use of this source code is subject to an MIT-style
// licence which can be found in the LICENSE file.
package main
import (
"image"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
// Cursor is used to interact with game entities at the given coordinates
type Cursor struct {
Coords image.Point
Width int
Image *ebiten.Image
Cooldown int // Wait to show off construction animation
BlinkCount int // Wait to blink the cursor
BlinkOn bool
}
// Update implements Entity
func (c *Cursor) Update(g *Game) error {
oldPos := c.Coords
tileSize := 7
hudOffset := 5
if c.Cooldown > 0 {
c.Cooldown--
}
blinkAfter := 40
c.BlinkCount = (c.BlinkCount + 1) % blinkAfter
if c.BlinkCount == 0 {
c.BlinkOn = !c.BlinkOn
}
// Movement controls
if inpututil.IsKeyJustPressed(ebiten.KeyS) {
c.Move(image.Pt(0, tileSize))
}
if inpututil.IsKeyJustPressed(ebiten.KeyW) {
c.Move(image.Pt(0, -tileSize))
}
if inpututil.IsKeyJustPressed(ebiten.KeyA) {
c.Move(image.Pt(-tileSize, 0))
}
if inpututil.IsKeyJustPressed(ebiten.KeyD) {
c.Move(image.Pt(tileSize, 0))
}
// Keep the cursor inside the map
if c.Coords.X < 0 ||
c.Coords.Y < hudOffset ||
c.Coords.X > g.Size.X ||
c.Coords.Y > g.Size.Y {
c.Coords = oldPos
}
return nil
}
// Move moves the player upwards
func (c *Cursor) Move(dest image.Point) {
c.Coords = c.Coords.Add(dest)
c.Cooldown = 0
c.BlinkOn = true
c.BlinkCount = 1
}
// Draw implements Entity
func (c *Cursor) Draw(g *Game, screen *ebiten.Image) {
if c.Cooldown != 0 {
return
}
if !c.BlinkOn {
return
}
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(
float64(c.Coords.X-c.Width/2),
float64(c.Coords.Y-c.Width/2),
)
screen.DrawImage(c.Image, op)
}
// NewCursor creates a new cursor struct at the bottom-left of the map
// It is shaped like a crosshair and is used to interact with the game
func NewCursor() *Cursor {
tileSize := 7
hudOffset := 6
tileCenter := 3
coords := image.Pt(
2*tileSize+tileCenter,
5*tileSize+tileCenter+hudOffset,
)
w := 3
i := image.NewPaletted(
image.Rect(0, 0, w, w),
NokiaPalette,
)
i.Pix = []uint8{
0, 1, 0,
1, 0, 1,
0, 1, 0,
}
return &Cursor{
Coords: coords,
Image: ebiten.NewImageFromImage(i),
Width: w,
}
}