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

I use libGDX (completely new to it actually) and Android. And I want to move the 3d object in the direction in which it is (at some speed). I think this is the main question, but he cannot find a direct answer for it. I have a Quaternion representing the rotation of the object (direction), and I have Vector3 representing the position of the object. The question is how to update Vector3's position using information from Quaternion to move the object in the direction represented by Quaternion. (An alternative to this could be the Quaternion extraction and yaw pitching step and get new angles using trigonometric calculations. But I think you need to use Vector3 and Quat to achieve this.)

+4
source share
1 answer

Quaternion is used to indicate rotation. First you need to indicate the direction when the rotation is not applied. For example, if you want to move along the X axis when rotation is not applied:

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

Make sure that the base direction is normal (length = 1), you can use the nor() method to ensure security:

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

Then you need to rotate the direction using Quaternion:

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

Now that you have a direction, you can scale it with the amount you want to move. You 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 perform several operations, for example:

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

Update: Adding working code from a Xoppa comment:

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

Source: https://habr.com/ru/post/1499354/


All Articles