我的游戏中有一个具有几个网格的对象,当我尝试以任一方式旋转其中任何一个网格时,它只围绕世界轴旋转,而不是它的局部轴。我在类构造函数中有一个rotation = Matrix.Identity
。每个网格都附加了这个类。然后这个类还包含方法:
...
public Matrix Transform{ get; set; }
public void Rotate(Vector3 newRot)
{
rotation = Matrix.Identity;
rotation *= Matrix.CreateFromAxisAngle(rotation.Up, MathHelper.ToRadians(newRot.X));
rotation *= Matrix.CreateFromAxisAngle(rotation.Right, MathHelper.ToRadians(newRot.Y));
rotation *= Matrix.CreateFromAxisAngle(rotation.Forward, MathHelper.ToRadians(newRot.Z));
CreateMatrix();
}
private void CreateMatrix()
{
Transform = Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(Position);
}
...
现在是Draw()方法:
foreach (MeshProperties mesh in model.meshes)
{
foreach (BasicEffect effect in mesh.Mesh.Effects)//Where Mesh is a ModelMesh that this class contains information about
{
effect.View = cam.view;
effect.Projection = cam.projection;
effect.World = mesh.Transform;
effect.EnableDefaultLighting();
}
mesh.Mesh.Draw();
}
修改
我担心要么把某个地方搞砸了,要么你的技术不起作用,这就是我所做的。每当我移动整个对象(Parent)时,我将其Vector3 Position;
设置为该新值。我还将每个MeshProperties Vector3 Position;
设置为该值。然后在MeshProperties的CreateMatrix()
内,我确实这样:
...
Transform = RotationMatrix * Matrix.CreateScale(x, y, z) * RotationMatrix * Matrix.CreateTranslation(Position) * Matrix.CreateTranslation(Parent.Position);
...
其中:
public void Rotate(Vector3 newRot)
{
Rotation = newRot;
RotationMatrix = Matrix.CreateFromAxisAngle(Transform.Up, MathHelper.ToRadians(Rotation.X)) *
Matrix.CreateFromAxisAngle(Transform.Forward, MathHelper.ToRadians(Rotation.Z)) *
Matrix.CreateFromAxisAngle(Transform.Right, MathHelper.ToRadians(Rotation.Y));
}
而Rotation
是Vector3
。
RotationMatrix
和Transform
都在构造函数中设置为Matrix.Identity
。
问题是如果我试图围绕例如Y轴旋转,他应该在“静止不动”的同时旋转一圈。但他在转动时四处走动。
答案 0 :(得分:1)
我不完全确定这是你想要的。我假设你有一个物体,有一些网格和位置偏离主要物体位置的位置和方向,你想要围绕它的局部轴相对于父物体旋转子物体。
Matrix.CreateTranslation(-Parent.Position) * //Move mesh back...
Matric.CreateTranslation(-Mesh.PositionOffset) * //...to object space
Matrix.CreateFromAxisAngle(Mesh.LocalAxis, AngleToRotateBy) * //Now rotate around your axis
Matrix.CreateTranslation(Mesh.PositionOffset) * //Move the mesh...
Matrix.CreateTranslation(Parent.Position); //...back to world space
当然,您通常会存储一个变换矩阵,该矩阵可以一步将网格从对象空间转换为世界空间,您也可以存储逆矩阵。您还始终将网格物体存储在对象坐标中,并仅将其移动到世界坐标以进行渲染。这会简化一些事情:
Matrix.CreateFromAxisAngle(Mesh.LocalAxis, AngleToRotateBy) * //We're already in object space, so just rotate
ObjectToWorldTransform *
Matrix.CreateTranslation(Parent.Position);
我认为您可以在示例中将Mesh.Transform设置为此并完全设置。
我希望这就是你要找的东西!
答案 1 :(得分:1)
问题是,当我将模型导出为.FBX时,枢轴点不在模型中心。从而使模型在旋转时移动。