inpututil: Add PressedKeys

Closes #770
This commit is contained in:
Hajime Hoshi 2021-04-07 01:48:13 +09:00
parent 6fe6543b4b
commit 0fcf5c8470
2 changed files with 21 additions and 9 deletions

View File

@ -27,6 +27,7 @@ import (
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/examples/keyboard/keyboard"
rkeyboard "github.com/hajimehoshi/ebiten/v2/examples/resources/images/keyboard"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
const (
@ -46,16 +47,9 @@ func init() {
}
type Game struct {
pressed []ebiten.Key
}
func (g *Game) Update() error {
g.pressed = nil
for k := ebiten.Key(0); k <= ebiten.KeyMax; k++ {
if ebiten.IsKeyPressed(k) {
g.pressed = append(g.pressed, k)
}
}
return nil
}
@ -73,7 +67,8 @@ func (g *Game) Draw(screen *ebiten.Image) {
// Draw the highlighted keys.
op = &ebiten.DrawImageOptions{}
for _, p := range g.pressed {
keys := inpututil.PressedKeys()
for _, p := range keys {
op.GeoM.Reset()
r, ok := keyboard.KeyRect(p)
if !ok {
@ -85,7 +80,7 @@ func (g *Game) Draw(screen *ebiten.Image) {
}
keyStrs := []string{}
for _, p := range g.pressed {
for _, p := range keys {
keyStrs = append(keyStrs, p.String())
}
ebitenutil.DebugPrint(screen, strings.Join(keyStrs, ", "))

View File

@ -161,6 +161,23 @@ func (i *inputState) update() {
}
}
// PressedKeys returns a set of currently pressed keyboard keys.
//
// PressedKeys is concurrent safe.
func PressedKeys() []ebiten.Key {
theInputState.m.RLock()
defer theInputState.m.RUnlock()
keys := make([]ebiten.Key, 0, len(theInputState.keyDurations))
for i, d := range theInputState.keyDurations {
if d == 0 {
continue
}
keys = append(keys, ebiten.Key(i))
}
return keys
}
// IsKeyJustPressed returns a boolean value indicating
// whether the given key is pressed just in the current frame.
//