From 0fcf5c84702c78ba58c5b41a10231319928a34b3 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Wed, 7 Apr 2021 01:48:13 +0900 Subject: [PATCH] inpututil: Add PressedKeys Closes #770 --- examples/keyboard/main.go | 13 ++++--------- inpututil/inpututil.go | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/examples/keyboard/main.go b/examples/keyboard/main.go index 5740f8c0a..77a2c9a3a 100644 --- a/examples/keyboard/main.go +++ b/examples/keyboard/main.go @@ -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, ", ")) diff --git a/inpututil/inpututil.go b/inpututil/inpututil.go index bbb3333f5..f380763a4 100644 --- a/inpututil/inpututil.go +++ b/inpututil/inpututil.go @@ -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. //