inpututil: Add AppendPressedKeys

Updates #1705
This commit is contained in:
Hajime Hoshi 2021-07-10 22:18:13 +09:00
parent 502455f5b2
commit a79c287bb7
3 changed files with 17 additions and 8 deletions

View File

@ -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) {

View File

@ -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
}

View File

@ -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.
//