java - 安卓。如何沿对象所面对的方向移动对象(使用 Vector3 和四元数)

标签 java android opengl-es libgdx

我正在使用 libGDX(实际上对它来说很新)和 Android。我想朝它所面对的方向移动 3d 对象(使用一些速度)。我认为这是一个基本问题,但找不到直接的答案。我有一个代表对象旋转(方向)的四元数,我有一个代表对象位置的 Vector3。问题是如何使用来自四元数的信息更新位置 Vector3,以便在四元数表示的方向上移动对象。 (另一种方法是从四元数中提取滚动俯仰和偏航,并通过应用三角计算获得新坐标。但我认为必须有一种方法可以使用 Vector3 和 Quat 来实现这一点。)

最佳答案

四元数用于指定旋转。当没有应用旋转时,您首先需要指定方向。例如,如果您想在未应用旋转时沿 X 轴移动:

Vector3 baseDirection = new Vector3(1,0,0);

确保基础方向被归一化(length = 1),你可以使用nor()方法来保证安全:

Vector3 baseDirection = new Vector3(1,0,0).nor();

接下来您需要使用四元数旋转方向:

Vector3 direction = new Vector3();
Quaternion rotation = your_quaternion;
direction.set(baseDirection);
direction.mul(rotation);

现在您已经确定了方向,您可以根据要移动的量来缩放它。您可能希望每一帧都执行此操作,具体取决于自上一帧以来耗时。

final float speed = 5f; // 5 units per second
Vector3 translation = new Vector3();
translation.set(direction);
translation.scl(speed * Gdx.graphics.getDeltaTime());

最后需要将翻译添加到位置

position.add(translation);

当然,根据您的实际实现,您可以批处理多个操作,例如:

translation.set(baseDirection).mul(rotation).scl(speed * Gdx.graphics.getDeltaTime());
position.add(translation);

更新: 从 Xoppa 的评论中添加工作代码:

translation.set(baseDirection).rot(modelInstance.transform).nor().scl(speed * delta)

关于java - 安卓。如何沿对象所面对的方向移动对象(使用 Vector3 和四元数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18485854/

相关文章:

java - 如何从 JSP 中的 URL 检索 jsessionid?

java - 包含图像的小程序在浏览器中运行时不会显示它们

java - 使用正则表达式提取文本的括号

android - 在运行 Google Play Services < 7.5.0 的设备上使用 GcmNetworkManager

android - Opengl es 2.0 试图将浮点值传递给 fragment 着色器 android

java - 如何在不失真的情况下将图像纹理到球体上

java - Java支持异常后恢复程序执行吗?

android - Meteor Mobile App 无法连接到服务器

android - Hello World App 无法在三星手机上运行

java - 立方体 3D 点旋转 X 和 Z