unity3d - 变换 Unity 坐标
问题描述
我在 Unity 的 A、B、C 处有三个对象。我想将它们的坐标转换为一个新的坐标系,其中点 A 作为新原点 (0, 0, 0),AB 作为沿新 x 轴的线,AC 作为沿新 y 轴的线。如何在这个新的坐标空间中获得 A、B、C 的新坐标?
我查看了 transform.InverseTransformPoint(),但我不确定如何让它在这里工作。
解决方案
更简单的 - 非数学 - 解决方案是
- 将对象 A、B、C 放在同一个父对象下
- 单独平移和旋转父对象而不是所有对象 => 让 Unity 为您计算
- 可以选择在完成后将它们再次放置在之前的位置 - 或者如果您希望仍然能够更改它们的 localPosition 和 localRotation ,请将它们保留在旋转的父级之下。
否则使用例如Transform.TransformPoint
没有养育
我将两者都添加到示例管理器中
public class CoordinateManager : MonoBehaviour
{
[Header("References")]
public Transform objectA;
public Transform objectB;
public Transform objectC;
[Header("Coordinate-System Settings")]
public Vector3 A;
public Vector3 AB;
public Vector3 AC;
[ContextMenu("Apply New Coordinates")]
public void ApplyNewCoordinates()
{
// just for making sure this transform is reset
transform.position = Vector3.zero;
transform.rotation = Quaternion.identity;
transform.localScale = Vector3.one;
// Make this object parent of objectA,objectB and objectC keeping their current transforms
// For reverting it later store current parents
var parentA = objectA.parent;
var parentB = objectB.parent;
var parentC = objectC.parent;
objectA.SetParent(transform);
objectB.SetParent(transform);
objectC.SetParent(transform);
// place this object to the new pivot point A
// and rotate it to the correct axis
// so that its right (X) vector euqals AB
// and its up (Y) vector equals AC
// Unity will handle the rotation accordingly
transform.position = A;
transform.right = AB;
transform.up = AC;
// Optionally reset the objects to the old parents
objectA.SetParent(parentA);
objectB.SetParent(parentB);
objectC.SetParent(parentC);
}
// Use this method to place another object in the coordinate system of this object
// without any parenting
public void SetPosition(Transform obj, Vector3 relativePosition)
{
// sets the obj to relativePosition in the
// local coordinate system of this rotated and translated manager
obj.position = transform.TransformPoint(relativePosition);
// adjust the rotation
// Quaternions are added by multiplying them
// so first we want the changed coordinate system's rotation
// then add the rotation it had before
obj.rotation = transform.rotation * obj.rotation;
}
// Only for visualization of the pivot point A and the
// AB(red) and AC(green) axis in the SceneView
private void OnDrawGizmos()
{
Gizmos.color = Color.white;
Gizmos.DrawWireSphere(A, 0.1f);
Gizmos.color = Color.red;
Gizmos.DrawLine(A, A + AB);
Gizmos.color = Color.green;
Gizmos.DrawLine(A, A + AC);
}
}
推荐阅读
- jquery - 如何将 jquery 添加到博客移动模板?
- java - 如何使用每个循环在数组中查找重复元素
- python-3.x - 无法使用 tf.metrics.recall
- jenkins - 如何在另一个作业成功完成后自动运行作业?
- python - 无法从 Python 脚本中的 HDFS 访问目录
- windows - IMFSourceReader::GetNativeMediaType 是否等同于 IMFMediaTypeHandler::GetMediaTypeByIndex?
- java - 如何使用同步线程将数据插入我的数据库表
- pandas - 如何在未定义的其他列上应用定义的函数
- javascript - 使用 IFrame 在 jQuery 中传播事件
- php - 如何使用 PHPMailer 将远程文件附加到电子邮件