LoginSignup
9

More than 5 years have passed since last update.

tmlibでオブジェクトをタッチに反応させる

Posted at

tmlib.js Advent Calendar 12/4分

以前引っ掛かって結構な時間悩んだ挙句に、phiさんに質問したら速攻回答頂いた件があるので覚書。
しょぼくて申し訳ありません(汗)

本題

tmlibでゲーム作ってると、オブジェクトをタッチした時になんらかの処理をさせたくなる時があります。
そういう時は…

javascript
app.currentScene.ontouchstart = function(e) {
    for (var i = 0; i < obj.length; i++) {
        if (obj[i].isHitPoint(e.pointing.x, e.pointing.y)) {
            //タッチしたので良い感じの処理
            obj[i].hogehoge();
        }
    }
}

という面倒な処理を書きがちです(少なくとも私は)

全部配列に保存しなきゃだしめんどいなーと思ってたら、tmlibにはオブジェクトをタッチした時にイベント発火させる機能がありました。

javascript
var obj = tm.display.RoundRectangleShape(width, height, param).addChildTo(this);
obj.interactive = true;
obj.boundingType = "circle";
obj.checkHierarchy = true;
obj.on("pointingstart", hogehoge);

interactiveフラグをtrueにするとタッチした時にイベント発火する様になります。
判定の種類(矩形、円形等)はboundingTypeで指定。

clickイベントを使用した場合checkHierarchytrueにすると反応しなくなるのでtouchstarttouchmovetouchend等を使用した方が良いらしいです(ここがハマったポイント)

親を持つ場合はcheckHierarchyフラグをtrueにしないと階層構造を考慮した判定が行われないので注意が必要です。

これでいちいちオブジェクトを配列に保存しなくてもタッチ判定が可能に!

サンプル(runstant)

runstant超便利

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
9