From a355d701ad2ad8342f7c06ba8c2d64b9bc81c0f1 Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Mon, 30 Apr 2018 04:34:15 +0900 Subject: [PATCH] inpututil: Replace JustDisconnectedGamepadIDs with IsGamepadJustDisconnected (#505) --- examples/gamepad/main.go | 15 ++++++++++++--- inpututil/inpututil.go | 20 +++++++------------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/examples/gamepad/main.go b/examples/gamepad/main.go index 52f5530c8..f55a4ab40 100644 --- a/examples/gamepad/main.go +++ b/examples/gamepad/main.go @@ -32,12 +32,21 @@ const ( screenHeight = 480 ) +var ( + gamepadIDs = map[int]struct{}{} +) + func update(screen *ebiten.Image) error { + // Log the gamepad connection events. for _, id := range inpututil.JustConnectedGamepadIDs() { log.Printf("gamepad connected: id: %d", id) + gamepadIDs[id] = struct{}{} } - for _, id := range inpututil.JustDisconnectedGamepadIDs() { - log.Printf("gamepad disconnected: id: %d", id) + for id := range gamepadIDs { + if inpututil.IsGamepadJustDisconnected(id) { + log.Printf("gamepad disconnected: id: %d", id) + delete(gamepadIDs, id) + } } ids := ebiten.GamepadIDs() @@ -56,7 +65,7 @@ func update(screen *ebiten.Image) error { pressedButtons[id] = append(pressedButtons[id], strconv.Itoa(int(b))) } - // Log some events. + // Log button events. if inpututil.IsGamepadButtonJustPressed(id, b) { log.Printf("button pressed: id: %d, button: %d", id, b) } diff --git a/inpututil/inpututil.go b/inpututil/inpututil.go index 8a10b5610..f1c5722e9 100644 --- a/inpututil/inpututil.go +++ b/inpututil/inpututil.go @@ -243,22 +243,16 @@ func JustConnectedGamepadIDs() []int { return ids } -// JustDisconnectedGamepadIDs returns gamepad IDs that are disconnected just in the current frame. +// IsGamepadJustDisconnected returns a boolean value indicating +// whether the gamepad of the given id is released just in the current frame. // -// JustDisconnectedGamepadIDs might return nil when there is no disconnected gamepad. -// -// JustDisconnectedGamepadIDs is concurrent safe. -func JustDisconnectedGamepadIDs() []int { - var ids []int +// IsGamepadJustDisconnected is concurrent safe. +func IsGamepadJustDisconnected(id int) bool { theInputState.m.RLock() - for id := range theInputState.prevGamepadIDs { - if _, ok := theInputState.gamepadIDs[id]; !ok { - ids = append(ids, id) - } - } + _, prev := theInputState.prevGamepadIDs[id] + _, current := theInputState.gamepadIDs[id] theInputState.m.RUnlock() - sort.Ints(ids) - return ids + return prev && !current } // IsGamepadButtonJustPressed returns a boolean value indicating