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

  1. //获取对象Transform组件下的position  
  2. float xx;  
  3. float yy;  
  4. float zz;  
  5. xx = GameObject.Find("objName").GetComponent<Transform>().position.x;  
  6. yy = GameObject.Find("objName").GetComponent<Transform>().position.y;  
  7. zz = GameObject.Find("objName").GetComponent<Transform>().position.z;  
  8.   
  9. //设置对象Transform组件下的position  
  10. GameObject.Find ("objName").GetComponent<Transform>().position = new Vector3(xx,yy,zz);  
  11.   
  12. //获取对象Transform 组件下的 rotation  
  13. float rx;  
  14. float ry;  
  15. float rz;  
  16. rx = GameObject.Find ("objName").GetComponent<Transform> ().localEulerAngles.x;  
  17. ry = GameObject.Find ("objName").GetComponent<Transform> ().localEulerAngles.y;  
  18. rz = GameObject.Find ("objName").GetComponent<Transform> ().localEulerAngles.z;  
  19.   
  20. //设置对象Transform组件下的 rotation   
  21. GameObject.Find ("objName").GetComponent<Transform> ().rotation = Quaternion.Euler(rx, ry, rz);  

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

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

猜你喜欢

转载自blog.csdn.net/chong90/article/details/66472538