首页 > 解决方案 > 将 Vector3 位置从一个相机视图复制到另一个

问题描述

在 Monogame(与此问题中的 XNA 相同)中,我需要将对象(3D 模型)从世界上的一个地方复制到另一个地方。问题是我不能将它们放在相同位置的一堆中,我想将它们粘贴到世界中,相对于我复制它们的相机具有完全相同的设置(距离和旋转)。

复制粘贴多个对象时,我真的没有运气。如果我复制一个对象,这很容易,因为我可以将它插入到相机前面(查看矩阵),但是当有很多具有特定设置的对象时,我真的无法将它们粘贴到场景中与相机相同的设置。

// I have code that clones my 3D objects when pressing CTRL+C
List<3DObject> copiedObjects = new List<3DObject>();
foreach(var obj in SelectedObjects){
    copiedObjects.Add(obj.DeepClone());
}

// i then have this code, when pasting in the objects (CTRL+V)
// calculate new position and rotation of pasted objects
// but it doesnt work as expected. And i cant figure out why.
foreach (var newObj in newObjects)
{
    if (newObj.ObjectLink == null)
    {
      #region NEW

      // newObj is a clone of another object in space A.
      // now, its pasted into space B (a different location with the camera (location and rotation)
      // this only works on objects that aren't rotated, and moved.
      // so it basically sucks.

      float pitch_delta = scene.Camera.Pitch - _copy_camera_pitch;
      float yaw_delta = scene.Camera.Yaw - _copy_camera_yaw;

      Vector3 camera_delta = _copy_camera_position - scene.Camera.Position;
      Vector3 newpos = newObj.Position - camera_delta;

      newObj.Position = Vector3.Transform(
        newpos, 
        Matrix.CreateTranslation(-scene.Camera.Position) 
        * scene.Camera.RotationMatrix 
        * Matrix.CreateTranslation(scene.Camera.Position) 
        * Matrix.Invert(newObj.TransformRotation));

      newObj.Rotation += new Vector3(MathHelper.ToDegrees(pitch_delta), MathHelper.ToDegrees(yaw_delta), 0);

      #endregion
    }
}

为了完成这项工作,我需要允许用户在世界上的一个地方,并选择 1 个或多个对象,然后按 CTRL+C。

然后用户可以“飞”到世界上不同的地方,然后按 CTRL+V。对象现在应该放置在世界中,与它们被复制的位置相同(相对于相机)

标签: c#mathmatrixcameramonogame

解决方案


推荐阅读