Libgdx使用Matrix4来表示对象的世界空间位置,旋转和缩放。
当我在我的代码中动画这些对象时,我希望将它们转换为保持位置,旋转和缩放分离的格式。 这样可以更容易地进行正确插值,以便为它们设置动画。
我将Scale和Position存储为Vector3s。 而旋转为四元数。
这是我的类,它存储这3个并转换为2和Matrix4;
public class PosRotScale {
private static String logstag="ME.PosRotScale";
Vector3 position = new Vector3();
Quaternion rotation = new Quaternion();
Vector3 scale = new Vector3(1f,1f,1f);
public PosRotScale(Vector3 position, Quaternion rotation, Vector3 scale) {
super();
this.position = position;
this.rotation = rotation;
this.scale = scale;
}
public PosRotScale(Matrix4 setToThis) {
this.setToMatrix(setToThis);
}
@Override
public String toString(){
Vector3 axis = new Vector3();
float angle = rotation.getAxisAngle(axis);
String stateAsString = "["+position.x+","+position.y+","+position.z+"]"
+ "["+axis.x+","+axis.y+","+axis.z+","+angle+"]"
+ "["+scale.x+","+scale.y+","+scale.z+"]";
return stateAsString;
}
public void setToMatrix(Matrix4 lastLocation) {
lastLocation.getTranslation(position);
lastLocation.getRotation(rotation);
lastLocation.getScale(scale);
}
public PosRotScale setToRotation(float i, float j, float k, float angleInDeg) {
rotation.set(new Vector3(i,j,k), angleInDeg);
return this;
}
public PosRotScale setToPosition(Vector3 newposition) {
position = newposition.cpy();
return this;
}
public PosRotScale setToScaling(Vector3 newscale) {
scale = newscale.cpy();
return this;
}
public Matrix4 createMatrix() {
return new Matrix4(position,rotation.nor(),scale);
}
}
(我为上面的代码段“道歉”并被解释为javascript道歉 - 我没有在Java的代码片段框中看到一个选项)
无论如何,为了测试这是否有效,我创建了一个测试状态并转换为它。 不幸的是,这些价值显然不匹配。 我预计旋转会稍微偏离(似乎是旋转的性质),但是规模显然是谨慎的。关于我做错了什么的指示?
测试代码;
PosRotScale startScaleAndRotation = new PosRotScale();
startScaleAndRotation.setToPosition(new Vector3(30f, 40f, 50f));
startScaleAndRotation.setToRotation(0f, 0f, 1f, 45);
startScaleAndRotation.setToScaling(new Vector3(0.5f, 2.5f,0.5f));
Gdx.app.log(logstag, " setting to: "+startScaleAndRotation.toString());
Matrix4 test = startScaleAndRotation.createMatrix();
PosRotScale test2 = new PosRotScale(test);
Gdx.app.log(logstag, " check after conversion: "+test2.toString());
结果:
setting to: [30.0,40.0,50.0][0.0,0.0,0.99999994,45.000004][0.5,2.5,0.5]
check after conversion: [30.0,40.0,50.0][0.0,0.0,1.811493,35.83953][1.8027757,1.8027754,0.5]