如何使用Three.js曲线作为沿着网格移动网格的路径

时间:2017-10-30 19:51:52

标签: javascript three.js coffeescript

构建动画,目前处于此状态:

http://jsfiddle.net/CoderX99/66b3j9wa/1/

请不要查看代码,它是从CoffeeScript编译的,并不利于您的理智。

对于你的想法,你看着一些“北欧”的景观,船只飘过来,汽车继续前进。左上角的黄色球体是汽车的代表,曲线代表蜿蜒的道路。

确切地说,

CatmullRomCurve3。黄色球体应该使用曲线来移动。

让我们使用闭合曲线,它的编码如下:

curveRoadNo2 = new THREE.CatmullRomCurve3([
  new THREE.Vector3( 15, roadHeight, 11 ),
  new THREE.Vector3( 12, roadHeight, 12 ),
  new THREE.Vector3( 11, roadHeight, 11 ),     
  new THREE.Vector3( 11, roadHeight, 9 ),
  new THREE.Vector3( 12, roadHeight, 8 ),
  new THREE.Vector3( 12, roadHeight, 5 ),
  new THREE.Vector3( 15, roadHeight, 3 ),
  new THREE.Vector3( 17, roadHeight, 7 ),
  new THREE.Vector3( 16, roadHeight, 8 ),
  new THREE.Vector3( 16, roadHeight, 9 ),
  new THREE.Vector3( 17, roadHeight, 11 )
] )

随机输入。

然后:

curveRoadNo2.closed = true
geometry = new THREE.Geometry()
geometry.vertices = curveRoadNo2.getPoints( 200 )
material = new THREE.LineBasicMaterial( { color : 0xa9c41e } )
curveObject = new THREE.Line( geometry, material )
scene.add( curveObject )

我想使用getPoint(t)getTangent(t)以某种方式制作动画,但我有点无能为力。

t = 0
animate = ->
  requestAnimationFrame animate

  t += 0.1
  vehicle.position = curveRoadNo2.getPoint(t)

  # (Not per se relevant)
  # The following works for animating the ship but makes 
  # absolutely no sense yet. 
  # Also this should move along some kind of an elliptical path,
  # showing up on to the scene, making a stop for unloading,
  # moving again. And loop.  
  # if 0 < t < 7
  #     v = t * 0.01
  #     ship.rotation.y += 26 * v ** 0.96 * Math.PI / 180
  #     ship.position.x += -6 * v
  #     ship.position.z +=  12 * v ** 1.3 

  renderer.render scene, camera
animate()

可以看出车辆一动不动。我查找了解决方案,但它们看起来都非常冗长和过于复杂。

JS答案当然也是受欢迎的。

1 个答案:

答案 0 :(得分:1)

您应该为位置定义另一个向量

  animate = function() {
    requestAnimationFrame(animate);
    t += 0.001;
    var pos =  curveRoadNo2.getPoint(t);
    vehicle.position.set(pos.x, pos.y, pos.z);
    // if 0 < t < 7
    //     v = t * 0.01
    //     ship.rotation.y += 26 * v ** 0.96 * Math.PI / 180
    //     ship.position.x += -6 * v
    //     ship.position.z +=  12 * v ** 1.3 
    return renderer.render(scene, camera);
  };

并且t + = 0.1太快了。所以,我把它变成了0.001。 如果您为Object3D或Mesh提供位置。 使用,

mesh.position.set(x, y, z);
object.position.set(newPos.x, newPos.y, newPos.z);

不仅是职位。对于轮换。

这更健康。