Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android. How to move object in the direction it is facing (using Vector3 and Quaternion)

I'm using libGDX (quite new to it in fact) and Android. And I want to move 3d object in the direction it is facing (using some speed). I thinks it's a basic question but can't find a straight nswer for it. I have a Quaternion representing object rotation(direction) and I have a Vector3 representing the object position. The question is how to update the position Vector3 using info from Quaternion in order to move object in the direction represented by Quaternion. (An alternative to this is extract roll pitch and yaw from Quaternion and get the new coords by applying trigonometric calculations. But i think there must be a way to achieve this using Vector3 and Quat.)

like image 429
Taras Avatar asked Dec 26 '22 21:12

Taras


1 Answers

Quaternion is used to specify a rotation. You first need to specify the direction when no rotation is applied. For example if you want to move along the X axis when no rotation is applied:

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

Make sure the base direction is normalized (length = 1),you can use the nor() method to be safe:

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

Next you'll need to rotate the direction using the Quaternion:

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

Now that you have the direction, you can scale it with the amount you want to move it. You'll probably want to do this every frame and depending on the time elapsed since the last frame.

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

Finally you need to add the translation to the position

position.add(translation);

Of course, depending on your actual implementation you can batch multiple operations, e.g.:

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

Update: Adding working code from Xoppa's comment:

translation.set(baseDirection).rot(modelInstance.transform).nor().scl(speed * delta)
like image 130
Xoppa Avatar answered Dec 28 '22 09:12

Xoppa