PixiJSでブラウザゲーム 04クリックイベントの画像
芽萌丸プログラミング部 @programming
投稿日 2020/02/21
更新日 2020/02/27 ✏

PixiJS

PixiJSでブラウザゲーム 04クリックイベント

PixiJSでブラウザゲーム 03エフェクトではキャラアイコンにエフェクトを掛けてみました。 今回は、クリックイベント(タップイベント)を実装してみたいと思います。 サンプルでは、キャラアイコンをクリック(タップ)するとアイコンが1秒間猫のアイコンに変化します。

目次:

前提

  • PixiJS v5.2.1

サンプルコード

04-handle-click-event.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>クリックイベントのハンドリング</title>
</head>

<body>
  <div>キャラをクリックすると1秒間だけ猫になります。</div>
  <div id="game"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.1.3/pixi.min.js"></script>
  <script>
  // Create a Pixi Application
  const app = new PIXI.Application({
    width: 512,
    height: 512,
    antialiasing: true,
    transparent: false,
    resolution: 1
  });

  // #game要素にpixiApp.view追加
  document.querySelector("#game").appendChild(app.view);

  //load an image and run the `setup` function when it's done
  PIXI.Loader.shared
    // リソースを登録
    // 第一引数は任意のキー、第二引数は実体パス
    .add("chara-1", "https://i.imgur.com/JNGbC6F.png")
    .add("chara-2", "https://i.imgur.com/H9smyaD.png")
    .add("chara-3", "https://i.imgur.com/xT6FStW.png")
    .add("explorer", "https://i.imgur.com/rWus6RK.png")
    .add("cat", "https://i.imgur.com/Fk2JkI5.png")
    .add("dungeon", "https://i.imgur.com/EzpxVBZ.png")
    .load(setup);

  //This `setup` function will run when the image has loaded
  function setup(loader, res) {
    //
    // ゲームシーンを作成
    //
    const gameScene = new PIXI.Container();
    app.stage.addChild(gameScene);
    // ダンジョン作成(ここで画面の大枠サイズを確定)
    const dungeon = new PIXI.Sprite(PIXI.utils.TextureCache["dungeon"]);
    gameScene.addChild(dungeon);
    // アニメーションを作成してシーンに追加
    const anim1 = createAnim(["chara-1", "chara-2", "chara-3", ]);
    anim1.x = 30;
    anim1.y = gameScene.height / 2 - anim1.height / 2;
    anim1.vx = 0;
    anim1.vy = 0;
    anim1.play();
    gameScene.addChild(anim1);
    //
    // NOTE: キャラにクリックイベントハンドラーをセット
    // 
    anim1.interactive = true;
    anim1
      .on("click", onClick)
      .on("touchstart", onClick);
  }

  /**
   * アニメーションスプライトオブジェクトを作成
   * @param  {Array<String>} imgs - imageパスの配列
   * @param  {Object} opts - [OPTIONAL] オプション @see PIXI.AnimatedSprite
   * @return {AnimatedSprite}
   */
  function createAnim(imgs, opts) {
    const textureArray = [];
    for (let i = 0; i < imgs.length; i++) {
      let texture = PIXI.Texture.from(imgs[i]);
      textureArray.push(texture);
    };
    const animatedSprite = new PIXI.AnimatedSprite(textureArray);
    animatedSprite.animationSpeed = (opts && opts.animationSpeed) ? opts.animationSpeed : 0.1;
    return animatedSprite;
  }

  function onClick(e) {
    console.log("onClick e:", e);
    const sprite = e.currentTarget;
    sprite.stop(); // NOTE: 一旦アニメ停止
    const prevTextures = sprite.textures; // アニメtexturesを保存しておく
    const newTexture = PIXI.utils.TextureCache["cat"]; // 猫のtexture
    sprite.texture = newTexture; // 画像を猫化
    setTimeout(() => {
      sprite.textures = prevTextures; // アニメtexturesを再設定
      sprite.play(); // NOTE: アニメ再生
    }, 1000);
  }
  </script>
</body>

</html>

実行

ひとこと

以上、クリックイベントとタッチイベントを実装する方法でした。 次回は方向カーソルキーでキャラアイコンを動かせるようにしてみたいと思います。

宣伝: PixiJSを使ったブラウザゲーム開発なら田中ソフトウェアラボにご相談ください!


芽萌丸プログラミング部
芽萌丸プログラミング部 @programming
プログラミング関連アカウント。Web標準技術を中心に書いていきます。フロントエンドからサーバサイドまで JavaScript だけで済ませたい人たちの集いです。記事は主に @TanakaSoftwareLab が担当。