将RigidBody指向一个方向(LookAt)

时间:2019-05-26 19:27:44

标签: math trigonometry godot

在Godot中,我有一个RigidBody,我想在3D空间中转动,使其指向某个方向。几乎是LookAt。我找到了this tutorial,并据此撰写了以下内容。

令我有些困惑的是,我不确定为什么只担心rotationAngle中的x轴-我是否也应该以其他方式实现其他东西?

public override void _IntegrateForces(PhysicsDirectBodyState state)
{
    // Push RigidBody in direction that it's facing
    Vector3 forwardForce = GetForwardForce();
    this.ApplyCentralImpulse(forwardForce);

    // Turn RigidBody to point in direction of world origin
    var targetPosition = Vector3.Zero;
    var currentDirection = -this.Transform.basis.z;
    var currentDistanceFromTarget = this.Translation.DistanceSquaredTo(targetPosition);

    GD.Print(currentDistanceFromTarget + " " + currentDirection);

    if(currentDistanceFromTarget > 50)
    {
        var targetDir = (targetPosition - this.Transform.origin).Normalized();

        var rotationAngle = Mathf.Acos(currentDirection.x) - Mathf.Acos(targetDir.x); // Why only x?

        var angularVelocity = Vector3.Up * (rotationAngle / state.GetStep());

        state.SetAngularVelocity(angularVelocity);
    }
}

这将工作到一定程度-如果新的currentDirection恰好与正Z轴匹配,那么它将以这种方式继续进行。

0 个答案:

没有答案