使用物理引擎在框架中移动相机

Move camera in aframe with physics engine

我在我的 aframe 应用程序中使用物理引擎,我希望当用户单击按钮时相机移动。

我想保留物理引擎属性,所以我使用 applyImpulse 作为运动方法。

这是我的示例场景:

<script src="https://aframe.io/releases/0.3.0/aframe.min.js"></script>
<script src="//cdn.rawgit.com/donmccurdy/aframe-extras/v2.3.0/dist/aframe-extras.min.js"></script>
<a-scene physics>
<!-- Camera -->
<a-entity id="cameraWrapper" geometry="box" dynamic-body="mass:1" position="0 1 0" width="2" height="1" depth="2" listener>
<a-entity id="camera" camera universal-controls position="0 1 0" rotation="0 0 0">
</a-entity>
</a-entity>
<a-grid static-body position="0 0 0"></a-grid>
</a-scene>
<div>
<a id="impulseButton">Move</a>
</div>

应该移动相机的javascript方法如下所示:

$(document).ready(function(){
  $("#impulseButton").on("click",function(){
    applyImpulse();
  });

function applyImpulse(){
    var x = 0;
    var y = 0;
    var z = 1;
    var el = $('#cameraWrapper')[0];
    el.body.applyImpulse(
       new CANNON.Vec3(x,y,z),
       new CANNON.Vec3().copy(el.body.position)
    );
  }
});

然而,移动似乎不是很流畅,当用户使用 WASD 控件时,cameraWrapper 实体仍保留在旧位置。如何使用 applyImpulse 平滑移动相机?

我认为这只是一个运动问题,所以 js/aframe 就是您所需要的。它应该看起来像这样。这只是一个快速的 n 脏,但应该给你这个想法。您可以搜索有关玩家移动的内容,并且会找到很多方法来做到这一点。只需将按键功能更改为按钮功能即可。

因此对于所有类型的实体(摄像头、灯光、播放器....)来说更像是这样:

this.camMove = function(){
        // delta = change in time since last call (seconds)
            delta = clock.getDelta(); 
            var mDir = 100 * delta;
            moves = false;

            var mButtons = ["button1", "button2", "button3"];
            for (var i = 0; i < mButtons.length; i++)
            {
                if ( mButtons >= 0 )
                    moves = true;
            }

            if ( mButtons === button1 )
                cam.translateX( mDir );
            if ( mButtons === button2 )
                cam.translateX( -mDir );
            if ( mButtons === button3 )
                cam.translateY( -mDir );
                ................
                ............
                ........
}

clock 应该是你的 aframe 中的一个函数,但我不确定它,因为我使用 three.js 来做这样的事情。

universal-controls component is a replacement for wasd-controls and look-controls that is compatible out of the box with aframe-physics-system. The key case where this is helpful is in preventing the camera from going through obstacles, which I don't recommend in VR,但对于桌面非 VR 应用程序仍然有用。

用法:

<a-entity camera universal-controls kinematic-body></a-entity>

添加了 kinematic-body 组件来检测播放器上的碰撞。这里有一个more complete example.


NOTE: Future versions of aframe-extras will probably not have support for kinematic-body and camera collisions, so you may be locked in at version 3.X.X. This is unfortunately necessary to support key VR cases better, like having physics for multiplayer experiences and running physics in a web worker for performance.