ThreeJS和转向行为

时间:2012-07-08 03:27:26

标签: three.js

我正在研究little side project,并且在使用Object3D定位时使转向算法在ThreeJS中运行良好有点困难。我目前看来的主要问题是角速度相当不受控制,一切都旋转太快。我希望能够限制一下。我提供了一个简化的代码示例。我想我差不多了,而且我看了一下四元数和Matrix4,但是无法理解它。以前有人有过这个问题吗?谢谢!

class Movement extends THREE.Object3D
    constructor: ->
        super
        @velocity = new THREE.Vector3()
        @speed = 4
        @ease = 7
        @hault = 2

    steer: (mode, target) ->
        if @speed is 0
            @velocity.set 0, 0, 0
            return true

        # velocity vector
        switch mode
            when 'arrive'
                fromPosition = @position
                toPosition = target
            when 'flee'
                fromPosition = target
                toPosition = @position
        @velocity.sub toPosition, fromPosition

        # calculate magnitude
        magnitude = @velocity.length()

        # hault
        if magnitude < @hault
            return true

        # limit angle of rotation
        # angle = Math.acos fromPosition.dot(toPosition) / fromPosition.length() / toPosition.length()
        # axis = new THREE.Vector3().cross fromPosition, toPosition .normalize()

        # speed limit
        if magnitude > @speed
            @velocity.divideScalar magnitude / @speed

        # easing
        if magnitude < @ease and mode is 'arrive'
            @velocity.multiplyScalar magnitude / (@ease + @hault / 2)

        # adjust for time
        @velocity.multiplyScalar GLOBAL.clock.getDelta()

        # update position and rotation
        @position.addSelf @velocity
        @rotation.y = Math.atan2 -@velocity.z, @velocity.x
        @rotation.z = Math.asin @velocity.y / @velocity.length()

1 个答案:

答案 0 :(得分:0)

尝试并修改此内容:

var qstart = new THREE.Quaternion();
    var qend = new THREE.Quaternion();
    var m  = new THREE.Matrix4();

    qstart.setFromRotationMatrix( MOVING_OBJECT.matrixWorld );
    qend.setFromRotationMatrix( m.lookAt( TARGET.position, MOVING_OBJECT.position, new THREE.Vector3( 0, 1, 0 ) ) );  

    MOVING_OBJECT.rotation.setEulerFromQuaternion( qstart.slerpSelf(qend, 0.015 ) );