threejs,将对象保留在另一个对象的表面上

时间:2013-07-03 08:22:02

标签: javascript three.js

我正在生成这样的地形几何:

     var geometry = new THREE.PlaneGeometry(100, 100, 100 , 100 );
     for (var i = 0, l = geometry.vertices.length; i < l; i++) {
          geometry.vertices[i].z  = Math.random() / 2;
     }
     geometry.computeFaceNormals();
     floor = new THREE.Mesh(geometry, floorMaterial);

并且有另一个应该在地板表面上行走的object3d。 我怎样才能知道我的物体上升或下降的程度?也许与raycaster。

将帖子 那么第一部分就解决了,但第二部分是raycaster返回的距离不正确,它以某种方式翻转每张脸。检查示例: http://myhtmltest.net76.net/raycast.html

1 个答案:

答案 0 :(得分:1)

正如你已经猜到的那样,THREE.Raycaster应该确实有效。

在更新循环中,您需要向下投射光线

var raycaster = new THREE.Raycaster();
raycaster.set(yourMovingObject.position, THREE.Vector3(0, -1, 0));

之后,您需要确定物体需要停止“坠落”的距离

var distance = 40; //set to your own measurements

最后但并非最不重要的是,检查交叉点

var velocity = new THREE.Vector3();

var intersects = raycaster.intersectObject(floor); //use intersectObjects() to check the intersection on multiple

//new position is higher so you need to move you object upwards
if (distance > intersects[0].distance) {        
    yourMovingObject.position.y += (distance - intersects[0].distance) - 1; // the -1 is a fix for a shake effect I had
}

//gravity and prevent falling through floor
if (distance >= intersects[0].distance && velocity.y <= 0) {
    velocity.y = 0;
} else if (distance <= intersects[0].distance && velocity.y === 0) {
    velocity.y -= delta ;
}

yourMovingObject.translateY(velocity.y);

这样的事情应该有效,但你必须根据自己的环境进行调整。