将3d对象对齐到相机位置

本文关键字:相机 位置 对齐 3d 对象 | 更新日期: 2023-09-27 18:09:07

我使用Viewport控件在AB4D PowerToys的帮助下可视化3d工具模型。

目前我试图对齐我的3D文本(这是一组线)到camera,所以它总是旋转到相机,看起来像2D文本。

是否可以将我的视觉转换绑定到我的相机位置?

将3d对象对齐到相机位置

终于自己找到了答案:

下面的代码应该在" camerachchanged "事件中调用。

private void UpdateTransforms()
    {
        if (!this.IsAttachedToViewport3D())
        {
            return;
        }
        Matrix3D view, projection;
        if (Camera.GetCameraMatrixes(out view, out projection))
        {
            Vector3D up = new Vector3D(view.M12, view.M22, view.M32);
            Vector3D look = new Vector3D(view.M13, view.M23, view.M33);
            Transform3D transform = Transform;
            Matrix3D inverseWorld = this.GetTransform();
            inverseWorld.Invert();
            look = inverseWorld.Transform(look);
            look.Normalize();
            up = inverseWorld.Transform(up);
            up.Normalize();
            Quaternion q = LookAtRotation(look, up);
            Transform3DGroup grp = new Transform3DGroup();
            grp.Children.Add(new RotateTransform3D(new QuaternionRotation3D(q), CenterPosition));
            grp.Children.Add(transform);
            Transform = grp;
            Camera.Refresh();
        }
    }
    private static Quaternion LookAtRotation(Vector3D lookAt, Vector3D upDirection)
    {
        Vector3D forward = lookAt;
        Vector3D up = upDirection;
        // Orthonormalize
        forward.Normalize();
        up -= forward * Vector3D.DotProduct(up, forward);
        up.Normalize();
        Vector3D right = Vector3D.CrossProduct(up, forward);
        Quaternion q = new Quaternion
        {
            W = Math.Sqrt(1.0 + right.X + up.Y + forward.Z) * 0.5
        };
        double w4Recip = 1.0 / (4.0 * q.W);
        q.X = (up.Z - forward.Y) * w4Recip;
        q.Y = (forward.X - right.Z) * w4Recip;
        q.Z = (right.Y - up.X) * w4Recip;
        return q;
    }