LoginSignup
2
0

PlayCanvasでの透視投影と平行投影のRayCastingについて

Last updated at Posted at 2020-08-24

PlayCanvasのRaycastingについて

PlayCanvasでレイキャストをどうやるのかとかは過去に書いているのでご参照を

PlayCanvasのレイキャストについて知ってみる
PlayCanvasのレイキャストをもっと見てみる

PlayCanvasの透視投影と正射影法の切り替えについて

CameraのEntityを選択して、インスペクターからProjectionで選択可能
スクリーンショット 2020-08-24 14.39.07.png
画像の Perspective が透視投影のこと、 Orthographic が平行投影のこと

透視投影

PlayCanvasでRayCastingを行う場合、公式でもコードは提示されている。
https://developer.playcanvas.com/en/user-manual/physics/ray-casting/

しかし、これの通りにやれば通常できるが、これは透視投影のカメラの時だけっぽい。
上記のURLからコードを引用します。

Raycast.prototype.doRaycast = function (screenX, screenY) {
    // The pc.Vec3 to raycast from (the position of the camera)
    var from = this.entity.getPosition();

    // The pc.Vec3 to raycast to (the click position projected onto the camera's far clip plane)
    var to = this.entity.camera.screenToWorld(screenX, screenY, this.entity.camera.farClip);

    // Raycast between the two points and return the closest hit result
    var result = this.app.systems.rigidbody.raycastFirst(from, to);

    // If there was a hit, store the entity
    if (result) {
        var hitEntity = result.entity;
        console.log('You selected ' + hitEntity.name);
    }    
};

(引用: https://developer.playcanvas.com/en/user-manual/physics/ray-casting/ )

平行投影

平行投影(Orthographic)で行いたい場合、上記のコードではできないので少し書き換える

ClickJump.prototype.initialize = function() {
    ~~省略~~
    this.rayStart = new pc.Vec3();
    this.rayEnd = new pc.Vec3();
    ~~省略~~
};

ClickJump.prototype.doRaycast = function (screenX, screenY) {
    var farClip = this.entity.camera.farClip;
    var nearClip = this.entity.camera.nearClip;
    this.entity.camera.screenToWorld(screenX, screenY, nearClip, this.rayStart);
    this.entity.camera.screenToWorld(screenX, screenY, farClip, this.rayEnd);

    var result = this.app.systems.rigidbody.raycastFirst(this.rayStart, this.rayEnd);

    if (result) {
        var hitEntity = result.entity;
        console.log('You selected ' + hitEntity.name);
    }    
};

ちょっとした備忘録でした

個人的に透視投影は3D感が強いけど、平行投影だと少し2D感が出て好きなのでよく使います。
その度にレイキャスト上手くいかなくて「どうやったっけ?」って毎度なっていたので備忘録にしました。

ちなみに平行投影のコードの書き方は、透視投影でも動くので普段からこっちの書き方にした方がいいかな

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