|
| 1 | +package inputviewer |
| 2 | + |
| 3 | +import ( |
| 4 | + "image" |
| 5 | + "image/color" |
| 6 | + "log" |
| 7 | + |
| 8 | + "github.com/hajimehoshi/ebiten" |
| 9 | + "github.com/hajimehoshi/ebiten/ebitenutil" |
| 10 | +) |
| 11 | + |
| 12 | +type Config struct { |
| 13 | + A, B, Z, R, Start InputButton |
| 14 | + CUp, CRight, CDown, CLeft InputButton |
| 15 | + |
| 16 | + J InputJoystick |
| 17 | +} |
| 18 | + |
| 19 | +type InputButton struct { |
| 20 | + Type string // (Button, Axis) |
| 21 | + ID int |
| 22 | + Dir int // -1 / 1 |
| 23 | + |
| 24 | + Pos image.Point |
| 25 | + Color color.RGBA |
| 26 | +} |
| 27 | + |
| 28 | +type InputJoystick struct { |
| 29 | + IDX, IDY int |
| 30 | + |
| 31 | + Pos image.Point |
| 32 | + Color color.RGBA |
| 33 | +} |
| 34 | + |
| 35 | +func (i InputJoystick) axes(id int) (float64, float64) { |
| 36 | + return ebiten.GamepadAxis(id, i.IDX), ebiten.GamepadAxis(id, i.IDY) |
| 37 | +} |
| 38 | + |
| 39 | +func (i InputButton) pressed(id int) bool { |
| 40 | + dir := 1.0 |
| 41 | + if dir < 0 { |
| 42 | + dir = -1 |
| 43 | + } |
| 44 | + |
| 45 | + switch i.Type { |
| 46 | + case "Button": |
| 47 | + return ebiten.IsGamepadButtonPressed(id, ebiten.GamepadButton(i.ID)) |
| 48 | + case "Axis": |
| 49 | + return ebiten.GamepadAxis(id, i.ID) > (dir * 0.15) |
| 50 | + } |
| 51 | + |
| 52 | + return false |
| 53 | +} |
| 54 | + |
| 55 | +type InputViewer struct { |
| 56 | + config Config |
| 57 | + id int |
| 58 | +} |
| 59 | + |
| 60 | +func NewInputViewer(config Config) *InputViewer { |
| 61 | + ids := ebiten.GamepadIDs() |
| 62 | + if len(ids) == 0 { |
| 63 | + log.Printf("warning: no gamepad found") |
| 64 | + return nil |
| 65 | + } |
| 66 | + id := ids[0] |
| 67 | + |
| 68 | + log.Printf("info: reading input from %s", ebiten.GamepadName(id)) |
| 69 | + |
| 70 | + return &InputViewer{ |
| 71 | + config: config, |
| 72 | + id: id, |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +func (iv *InputViewer) Draw(screen *ebiten.Image) { |
| 77 | + if iv == nil { // allow ignoring input viewer |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + for _, v := range []*InputButton{ |
| 82 | + &iv.config.A, &iv.config.B, |
| 83 | + &iv.config.Z, &iv.config.R, |
| 84 | + &iv.config.Start, |
| 85 | + &iv.config.CUp, &iv.config.CRight, |
| 86 | + &iv.config.CDown, &iv.config.CLeft, |
| 87 | + } { |
| 88 | + if !v.pressed(iv.id) { |
| 89 | + continue |
| 90 | + } |
| 91 | + |
| 92 | + ebitenutil.DrawRect( |
| 93 | + screen, |
| 94 | + float64(v.Pos.X), float64(v.Pos.Y), |
| 95 | + 2, 2, |
| 96 | + color.RGBA{v.Color.R, v.Color.G, v.Color.B, 0xFF}, |
| 97 | + ) |
| 98 | + } |
| 99 | + |
| 100 | + j := iv.config.J |
| 101 | + x, y := j.axes(iv.id) |
| 102 | + ebitenutil.DrawRect( |
| 103 | + screen, |
| 104 | + float64(j.Pos.X)+4.0*x, |
| 105 | + float64(j.Pos.Y)+4.0*y, |
| 106 | + 2, 2, |
| 107 | + color.RGBA{j.Color.R, j.Color.G, j.Color.B, 0xFF}, |
| 108 | + ) |
| 109 | +} |
0 commit comments