Watch the associated video on YouTube or MakerTube

Introduction #
In this tutorial we will learn how to handle mouse and touchscreen input using the Ebitengine game engine.
The code for this tutorial is available here. Please consider donating if you find this tutorial helpful.
Mouse Buttons #
Ebitengine defines the following mouse button constants:
ButtonLeft
ButtonMiddle
ButtonRight
The middle button refers to the scroll wheel found on most (but not all) mice.
Handling Mouse Input #
When we want to detect whether or not a mouse button is currently pressed, we call ebiten.IsMouseButtonPressed.
When we want to detect whether or not a mouse button is just starting to be pressed this tick, we call inpututil.IsMouseButtonJustPressed.
The difference between the two is that IsMouseButtonPressed
always returns true
every tick the button continues to be pressed, while IsMouseButtonJustPressed
only
returns true
the first tick the button press event is observed.
We can check whether a mouse button has just been released by calling inpututil.IsMouseButtonJustReleased.
// Update is where we update the game state.
func (g *game) Update() error {
// ...
jump := inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft)
// ...
}
In this game, clicking anywhere on the screen will produce the same result. Thus, we only check for new press events.
However, we could retrieve the current position of the mouse cursor by calling ebiten.CursorPosition.
On devices without a mouse, ebiten.CursorPosition
returns (0, 0).
Touch IDs #
Ebitengine touch IDs are integers referencing touchscreen press events. A new ID is assigned for each new press.
Multi-touch is supported, meaning any number of concurrent press events may be handled individually.
Handling Touchscreen Input #
To check for any new touchscreen press events, we call inpututil.AppendJustPressedTouchIDs:
type game struct {
// ...
// All touch IDs.
touchIDs []ebiten.TouchID
}
// Update is where we update the game state.
func (g *game) Update() error {
// ...
// Pass touchIDs as an empty slice to AppendJustPressedTouchIDs.
// Any allocated memory will be reused.
g.touchIDs = inpututil.AppendJustPressedTouchIDs(g.touchIDs[:0])
if len(g.touchIDs) != 0 {
jump = true
}
// ...
}
In this game, pressing anywhere on the screen will produce the same result. Thus, we only check for new press events.
However, we could retrieve the current position of an ongoing press by calling ebiten.TouchPosition.
When the press referenced by a touch ID is released, ebiten.TouchPosition
returns (0, 0).
Stay tuned for the next tutorial, Building Your Ebitengine Game for Web Browsers.
Please consider donating if you found this tutorial helpful.