当前位置:网站首页>Transform 相对位置变换,坐标系转换
Transform 相对位置变换,坐标系转换
2022-08-04 05:57:00 【渐末竹】
1.在开发的时候有遇到需要做对某一个对象进行坐标系转换,比如需要一个对象a,需要时刻保持相对于A不变。 最简单的时 将a作为A的子物体。 这时候无论A怎么变换,a都相对A 是一致的。 这样做肯定是没问题的,而且简单。
2.但是呢! 也会碰到情况复杂,选择a 设置为A的子物体,可能会影响到其他的逻辑,所以不能做样做。那这时候就得通过计算来得到。 这里就要做坐标系转换。那么就需要用到Transform.TransformPoint 以及Transform.TransformDirection 。
3. 首先是做位移的计算。 对某个点进行坐标系转换,用 Transform.InverseTransformDirection 和 Transform.TransformPoint 就可以。
在初始化的时候 使用 Transform.InverseTransformDirection() 方法,将a的世界坐标,转化为相对于A的局部坐标。保存这个局部坐标,这个就是需要a一致保持的位置信息。
然后在A姿态发生变化时, 通过 Transform.TransformPoint 可以将刚保存的局部坐标,从A 坐标系转化到世界坐标系,这时候将得到的坐标赋值给a. 位置就可以实现相对A不变。
4. 然后就是要做角度也要相对A不变。 同样需要保存一个局部的角度信息
(1)第一种,直接保存相对的四元数信息。如下
Quaternion.Inverse(a.rotation) * A.rotation
在A发生变化后,在执行 Quaternion rot = defaultRot * A.rotation;
rot即是变化后a现对A角度一致的rotation.
(2)第二种 采用 transform.TransformDirection 。 这个是对向量进行坐标系转换,,所以就选一个轴在做。 用Forward 比较方便。
首先依旧是初始化的时候,记录相对方向。如下
DefauleDrec = A.InverseTransformDirection(a.forward);
在A发生变化后,在执行
Vector3 Rot01 = A.TransformDirection(DefauleDrec); // 将方向从A的坐标系转化到世界坐标系。
a.rotation = Quaternion.LookRotation(Rot01, transform.up); //然后在将旋转赋值到a
测试代码如下:
public Transform A;
public Transform a;
private Vector3 defaultPos=Vector3.zero;
private Vector3 DefauleDrec = Vector3.zero;
private Quaternion defaultRot;
// Start is called before the first frame update
void Start()
{
//记录子级初始的相对于父级的角度姿态。
DefauleDrec = A.InverseTransformDirection(a.forward);
defaultPos= A.InverseTransformPoint(a.position);
defaultRot = Quaternion.Inverse(a.rotation) * A.rotation;
}
// Update is called once per frame
void Update()
{
//方法一
//变换之后的位置计算
Vector3 Pos = A.TransformPoint(defaultPos);
//变换之后的放向计算
Quaternion rot = defaultRot * A.rotation;
a.position = Pos;
a.rotation = rot;
// 方法二
//变换之后的位置计算
Vector3 Pos01 = A.TransformPoint(defaultPos);
//变换之后的放向计算
Vector3 Rot01 = A.TransformDirection(DefauleDrec);
a.position = Pos01;
a.rotation = Quaternion.LookRotation(Rot01, transform.up);
}
边栏推荐
猜你喜欢
Database: Organize Four Practical SQL Server Scripting Functions
MAML原理讲解和代码实现
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
在线公众号文章内容转音频文件实用小工具
Hardware Knowledge: Introduction to RTMP and RTSP Traditional Streaming Protocols
如何画好业务架构图。
A priori box (Anchor) in target detection
MMDeploy部署实战系列【第四章】:onnx,tensorrt模型推理
SystemVerilog-条件(三元)运算符
MySQL内存淘汰策略
随机推荐
MySQL面试题大全(陆续更新)
Triton部署mmdeploy导出的TensorRT模型失败篇
ubuntu18.04安装redis教程
软件:给大家推荐一款国产非常好用的效率软件uTools
CSRF和SSRF漏洞
子空间结构保持的多层极限学习机自编码器(ML-SELM-AE)
数组的一些方法
E-R图总结规范
类图规范总结
MySQL基础(DDL、DML、DQL)
MySQL内存淘汰策略
Provide 和 Inject 的用法
pycharm专业版使用
ResNet详解:ResNet到底在解决什么问题?
电脑知识:台式电脑应该选择品牌和组装,值得收藏
MAML principle explanation and code implementation
窥探晶体世界的奥秘 —— 230种空间群晶体结构模型全在这里
数据特征预处理——缺失值的查看方式及处理
Sql优化总结!详细!(2021最新面试必问)
专题讲座7 计算几何 学习心得