From a79c287bb774494088cf550e28bb4f6865a62b87 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Sat, 10 Jul 2021 22:18:13 +0900 Subject: [PATCH] inpututil: Add AppendPressedKeys Updates #1705 --- examples/flappy/main.go | 8 +++++--- examples/keyboard/main.go | 2 +- inpututil/inpututil.go | 15 +++++++++++---- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/examples/flappy/main.go b/examples/flappy/main.go index 1ec3b60b9..3b2bc638b 100644 --- a/examples/flappy/main.go +++ b/examples/flappy/main.go @@ -177,6 +177,7 @@ type Game struct { gameoverCount int + keys []ebiten.Key gamepadIDs []ebiten.GamepadID } @@ -197,8 +198,9 @@ func (g *Game) init() { } } -func isAnyKeyJustPressed() bool { - for _, k := range inpututil.PressedKeys() { +func (g *Game) isAnyKeyJustPressed() bool { + g.keys = inpututil.AppendPressedKeys(g.keys[:0]) + for _, k := range g.keys { if inpututil.IsKeyJustPressed(k) { return true } @@ -207,7 +209,7 @@ func isAnyKeyJustPressed() bool { } func (g *Game) jump() bool { - if isAnyKeyJustPressed() { + if g.isAnyKeyJustPressed() { return true } if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) { diff --git a/examples/keyboard/main.go b/examples/keyboard/main.go index 8fa1d8744..ea121e053 100644 --- a/examples/keyboard/main.go +++ b/examples/keyboard/main.go @@ -52,7 +52,7 @@ type Game struct { } func (g *Game) Update() error { - g.keys = inpututil.PressedKeys() + g.keys = inpututil.AppendPressedKeys(g.keys[:0]) return nil } diff --git a/inpututil/inpututil.go b/inpututil/inpututil.go index 06dcc2e1e..812af885c 100644 --- a/inpututil/inpututil.go +++ b/inpututil/inpututil.go @@ -166,14 +166,14 @@ func (i *inputState) update() { } } -// PressedKeys returns a set of currently pressed keyboard keys. +// AppendPressedKeys append currently pressed keyboard keys to keys and returns the extended buffer. +// Giving a slice that already has enough capacity works efficiently. // -// PressedKeys is concurrent safe. -func PressedKeys() []ebiten.Key { +// AppendPressedKeys is concurrent safe. +func AppendPressedKeys(keys []ebiten.Key) []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 @@ -183,6 +183,13 @@ func PressedKeys() []ebiten.Key { return keys } +// PressedKeys returns a set of currently pressed keyboard keys. +// +// Deprecated: as of v2.2.0. Use AppendPressedKeys instead. +func PressedKeys() []ebiten.Key { + return AppendPressedKeys(nil) +} + // IsKeyJustPressed returns a boolean value indicating // whether the given key is pressed just in the current frame. //