Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ebitenでスマホのマルチタッチ座標を表示してみたの

Last updated at Posted at 2018-07-31

ebitenでマルチタッチ

image.png

ebitenを使って制作中のゲームを、スマホアプリとしても動作するようにしようと企んでおります。そこで、タッチ操作の扱いを学ぶために「マルチタッチの座標を画面に表示するサンプル」を作ってスマホで動かしてみました:blush:

サンプルコードは、以下のリポジトリにあります。:octocat:

kemokemo/ebiten-sketchbook:
Sketchbook to do various trials using the ebiten library - touch-point

使用環境

実装内容の説明

タッチ位置情報を取得してみる

使用するebiten側のメソッドを順にみてみましょう。
まずTouchIDsメソッドでIDの配列を取得します。

input.go
// 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)の位置情報を取得します。

input.go
// 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は小さい数字からタッチした順になっています。

main.go
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部品のあたり判定とかを実装すれば、画面操作ができそうですね!
どんどん筋トレしようと思います! :muscle:

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?