Unity3D(四)获取与设置对象Transform组件下的position,rotation

//获取对象Transform组件下的position
float
xx; float yy; float zz; /** * 初始化保留整体模型位置,用于还原模型位置(Position) * transform.position 获取世界位置 * transform.localPosition 获取本地位置 **/ xx = GameObject.Find("objName").GetComponent<Transform>().position.x; yy = GameObject.Find("objName").GetComponent<Transform>().position.y; zz = GameObject.Find("objName").GetComponent<Transform>().position.z; //设置对象Transform组件下的position GameObject.Find ("objName").GetComponent<Transform>().position = new Vector3(xx,yy,zz);

  其中postion的获取与设置比较简单,需要注意的是rotation的获取  不能直接用rotation.x 获取,这样得到的数是一个-1到1的小数,需要用localEulerAngles.x的方法获取

rotation的设置同样值得注意,需要用到四元数 Quaternion.Euler(x,y,z);的方式实现。

//获取对象Transform 组件下的 rotation
float rx;  float ry;  float rz;
/**
 * 初始化保留整体模型角度,用于还原模型角度(Rotation)
 * transform.eulerAngles 获取世界模型角度
 * transform.localEulerAngles 获取本地模型角度
 **/
rx = GameObject.Find ("objName").GetComponent<Transform> ().localEulerAngles.x;
ry = GameObject.Find ("objName").GetComponent<Transform> ().localEulerAngles.y;
rz = GameObject.Find ("objName").GetComponent<Transform> ().localEulerAngles.z;
//设置对象Transform组件下的 rotation GameObject.Find ("objName").GetComponent<Transform> ().rotation = Quaternion.Euler(rx, ry, rz);

   参考文章:https://blog.csdn.net/weiming8517/article/details/50960918?utm_source=blogxgwz7

猜你喜欢

转载自www.cnblogs.com/lotuses/p/11596422.html
今日推荐