Libgdx How to rotate a 3D model on multiple axes w

2019-02-22 08:09发布

I'm trying to rotate a 3D model on multiple axes at once using the phone's accelerometers. When I do this, I use setToRotation() however, this only does one axis at a time.

For example:

  ModelInstance modelInstance = instances.first(); 

  //ROLL
  modelInstance.transform.setToRotation(Vector3.Z, phoneAccel.y*9);
  //PITCH
  modelInstance.transform.setToRotation(Vector3.X, phoneAccel.z*9);

The phone is in forced-landscape mode. I get the instance of the model I want to rotate.

I set the Vector3 phoneAccel based on Gdx.input.getAccelerometerX/Y/Z().

In the above example, both lines of code work correctly, but only independently. When I try to use both (one after another) the first rotate (ROLL) is removed. I would have thought the two rotation matrices would be cumulated, ie, the Z Axis is applied a rotation, and then the X Axis is applied a rotation.

Do I need to create my own cumulative rotation matrix, and then apply that at the end?

Any thoughts? Cheers

2条回答
The star\"
2楼-- · 2019-02-22 08:39

Matrix4#setToRotation will remove any other transformation (like rotation) previously set (hence the name "setTo"). To add a rotation transformation to an already rotated matrix, use the rotate method instead. This will post-multiply the transformation.

modelInstance.transform.setToRotation(Vector3.Z, phoneAccel.y*9);
modelInstance.transform.rotate(Vector3.X, phoneAccel.z*9);

However this will not produce your desired result, since you want the rotations to independent from each other (the rotation around the Z axis should not influence the rotation around the X axis for example). For this you can use euler angles:

modelInstance.transform.setFromEulerAngles(yaw, pitch, roll);
查看更多
你好瞎i
3楼-- · 2019-02-22 08:51

The method setToRotation sets the model to this rotation, as the name says. This means, that you "overwrite" the rotation arround the Z-Axis and set it to a rotation ONLY arround the X-Axis.

There are different ways to do what you want to achieve:

  • You can use Quaternions like @noone said.
  • You can use rotate. If you do that you need to stor your current rotation in forexample a Vector2, where the x value is the current rotation arround Z-Axis and the y value is the rotation arround the X-Axis.
  • You can use setToRotation, with a custom axis, which you construct our of the phoneAccel values.

The setToRotation method gives you the posibility to define a Vector3 direction and a Vector3 face, defining which face should look to this direction. For example: modelInstance.transform.setToRotation(Vector3.Z, Vector3.Y) will make his top look inot Z-Direction. With a Vector3(0, -1, 0) his bottom (maybe his feet) will look in that direction.

Hope it is clear

查看更多
登录 后发表回答