LoginSignup
1
0

More than 3 years have passed since last update.

PlayCanvas x tween.jsを使って押された画像の位置にカメラを移動させる

Last updated at Posted at 2020-10-05

PlayCanvasとTween.jsを使用して、設置したピンが押されたときにピンの位置にカメラを移動させます。

まず実行結果はこちらになります。

(ブラウザで実行できます)
https://playcanv.as/p/ZsHC33Oc/

Tween.jsについてはこちらを使用しています。使用する場合には、こちらからtween.jsをダウンロードし、プロジェクトに追加してください。
https://github.com/playcanvas/playcanvas-tween

ピンを設置


こちらがPlayCanvasのプロジェクトです。このプロジェクトはCameraにはFlyCameraの設定がされているプロジェクトになります。

  • Elementコンポーネント
  • Buttonコンポーネント
  • Scriptコンポーネント
    この3つのコンポーネントを持ったエンテティを作成します。

Elementコンポーネント

Elementコンポーネントを追加し設定を行います。今回は、マウスでクリックされた際にボタンの反応をさせるためにUse Inputにチェックを入れます。

  1. 画面上にピンとして表示させたい画像をElementコンポーネントのTextureに設定
  2. Width, Heightの大きさを設定(画像をアップロードした場合、そのままテクスチャの解像度が設定されますのでそちらを表示させたい大きさに変更)
  3. Use Inputを有効にする

Buttonコンポーネント


Buttonコンポーネントの設定をします。HoverやPressedのTint Colorをここで設定することができます。

  1. Imageプロパティに自身のエンテティを設定します。

Scriptコンポーネント

下記のpin.js、を適用し、ピンがクリックされた際に移動常にカメラを向き続ける処理の機能を追加します。

  1. pin.jsを保存
const Pin = pc.createScript('pin');
Pin.attributes.add("camera", {type: "entity"}) // CameraをAttributeとして設定

Pin.prototype.initialize = function() {
    //ボタンがクリックされたらthis.moveの関数を呼び出す
    this.entity.button.on(pc.EVENT_MOUSEUP, this.move, this)
    this.entity.button.on(pc.EVENT_TOUCHSTART, this.move, this)
};

Pin.prototype.move = function(){
    //tweenを使用してカメラを移動させる
    const {x, y, z} = this.entity.getPosition().scale(1.2) //ピンの位置を取得
    const cameraPosition = this.camera.getLocalPosition() // カメラの位置を取得
    const tween  = this.camera.tween(cameraPosition).to({x, y: cameraPosition.y, z},  2, pc.QuinticIn) // カメラの位置からピンの位置へ移動
    tween.start() // tween開始
}
Pin.prototype.update = function() {
    this.entity.lookAt(this.camera.getPosition()); // ピンを常にカメラを向き続ける
    this.entity.rotateLocal(0, 180, 0); // LookAtでは逆向きになっているので反転させる
}

  1. Parseボタンをクリックしスクリプトの更新をします
  2. cameraのAttributesに移動させるカメラを追加します。

このような形でクリックされた場所にカメラを移動させることができます。


https://playcanv.as/p/ZsHC33Oc/

PlayCanvas開発で参考になりそうな記事の一覧です。 入門 応用 その他の記事はこちらになります。 その他関連 - [PlayCanvasタグの付いた記事一覧](https://qiita.com/tags/playcanvas)

PlayCanvasのユーザー会のSlackを作りました!

少しでも興味がありましたら、ユーザー同士で解決・PlayCanvasを推進するためのSlackを作りましたので、もしよろしければご参加ください!

日本PlayCanvasユーザー会 - Slack

1
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
1
0