ebitenでマルチタッチ
ebitenを使って制作中のゲームを、スマホアプリとしても動作するようにしようと企んでおります。そこで、タッチ操作の扱いを学ぶために「マルチタッチの座標を画面に表示するサンプル」を作ってスマホで動かしてみました
サンプルコードは、以下のリポジトリにあります。
kemokemo/ebiten-sketchbook:
Sketchbook to do various trials using the ebiten library - touch-point
使用環境
- go version go1.10.2 windows/amd64
- ebiten rev. c39c211d1fe0744b3a2315a122f89c7074a54a49
- gomobile version +bf2d30a Sun Apr 29 17:04:17 2018
- Android NDK r16b
実装内容の説明
タッチ位置情報を取得してみる
使用するebiten
側のメソッドを順にみてみましょう。
まずTouchIDs
メソッドでID
の配列を取得します。
// TouchIDs returns the current touch states.
//
// TouchIDs returns nil when there are no touches.
// TouchIDs always returns nil on desktops.
//
// TouchIDs is concurrent-safe.
func TouchIDs() []int {
var ids []int
for _, t := range ui.AdjustedTouches() {
ids = append(ids, t.ID())
}
return ids
}
次にTouchPosition
に先程取得したID
を渡して、(x,y)
の位置情報を取得します。
// TouchPosition returns the position for the touch of the specified ID.
//
// If the touch of the specified ID is not present, TouchPosition returns (0, 0).
//
// TouchPosition is cuncurrent-safe.
func TouchPosition(id int) (int, int) {
for _, t := range ui.AdjustedTouches() {
if t.ID() == id {
return t.Position()
}
}
return 0, 0
}
表示してみる
で、実際に位置情報を取得して画面に表示してみたのが以下の実装です。
取得した[]int型
のIDs
をソートしてから使います。ID
は小さい数字からタッチした順になっています。
func update(screen *ebiten.Image) error {
message := "touching points:\n"
IDs := ebiten.TouchIDs()
sort.Slice(IDs, func(i, j int) bool {
return IDs[i] < IDs[j]
})
for _, id := range IDs {
x, y := ebiten.TouchPosition(id)
message = fmt.Sprintf("%v x: %v, y: %v\n", message, x, y)
}
ebitenutil.DebugPrint(screen, message)
return nil
}
次はタッチ位置情報とUI部品のあたり判定とかを実装すれば、画面操作ができそうですね!
どんどん筋トレしようと思います!