1

I'm trying to draw the trajectory of a projectile motion with threejs. Which is the best way to do that? Here is an example of it: http://www.physgl.org/index.php/welcome/logout Try the projectile motion demo and click run.

I thought of drawing a second mesh that follows the previous movement by obtaining the position of the mesh as it's moving, but that did not work. This is what I tried (this code) to get the position of the object moving:

box.geometry.computeBoundingBox();

    var boundingBox = box.geometry.boundingBox;

    var position = new THREE.Vector3();
    position.subVectors( boundingBox.max, boundingBox.min );
    position.multiplyScalar( 0.5 );
    position.add( boundingBox.min );

    position.applyMatrix4( box.matrixWorld );

    console.log(position.x + ',' + position.y + ',' + position.z);

Please Help. Thanks.

4

1 回答 1

1

有几种方法可以跟踪轨迹。在这里,除了解决方案之外,我还将向您展示一些您想要的行为的替代方案。

解决方案 A:标记每个步骤

在您的 Physijs 应用程序中,当更新完成时您应该有一个scene.simulate调用和一个事件侦听器,以便您可以在渲染过程中分开循环物理。添加一些额外的代码以在场景中的每一步放置某种标记应该不会太难,最好不要包含太多额外的顶点(即不太复杂):

var markSize = 2; // Tweak this to set marker size

var markGeom = new THREE.BoxGeometry(markSize, markSize, markSize, 1, 1, 1);
var markMat = new THREE.MeshBasicMaterial({color: "blue"});

scene.addEventListener("update", function(){

    // Generate a box where projectile was last moved
    var marker = new THREE.Mesh(markGeom.clone(), markMat);
    marker.position.copy(projectile.position);

    // Display position!
    scene.add(marker);

    // Keep simulation going
    scene.simulate(undefined, 2);
});

在此代码中,projectile是引用您的抛射物 Physijs 网格的变量。请注意,您不应该为您的渲染循环格式化它,因为您可能正在使用requestAnimationFrame,当窗口(或选项卡)失去焦点时,它会停止调用您的渲染循环。当某些客户这样做并获得混乱的轨迹时,这将不会令人愉快。另外,这直接与您的 Physijs 步进相关联,这使得它非常精确。

解决方案 B:动态箭头

这可能是您最初想要的。它会创建一个箭头来显示弹丸的方向和速度:

// Constructor: direction, origin, length, color in hexadecimal
var arrowMark = new THREE.ArrowHelper(
    new THREE.Vector3(0, 1, 0), projectile.position, 0, 0x884400);

function drawDir(){
    var pvel = projectile.getLinearVelocity();

    // Update arrow
    arrowMark.position.set(projectile.position);
    arrowMark.setDirection(pvel.normalize());
    arrowMark.setLength(pvel.length());
}

是的,这很容易。再次projectile引用您的弹丸 Physijs 网格。只需调用drawDir每个渲染调用,您就可以开始了!

THREE.ArrowHelper文档 ArrowHelper

于 2016-10-22T17:41:28.380 回答