1 Application类

2 Camera类

3 GameObject类

4 HideFlags类

5 Mathf类

6 Matrix4x4类

7 Object类

8 Quaternion类

9 Random类

10 Rigidbody类

11 Time类

12 Transform类

13 Vector2类

14 Vector3类

1 Application类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class DataPath_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //四种不同的path,都为只读
  9. //dataPath和streamingAssetsPath的路径位置一般是相对程序的安装目录位置
  10. //persistentDataPath和temporaryCachePath的路径位置一般是相对所在系统的固定位置
  11. Debug.Log("dataPath:" + Application.dataPath);
  12. Debug.Log("persistentDataPath:" + Application.persistentDataPath);
  13. Debug.Log("streamingAssetsPath:" + Application.streamingAssetsPath);
  14. Debug.Log("temporaryCachePath:" + Application.temporaryCachePath);
  15. }
  16. }

DataPath

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LoadedLevel_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //返回当前场景的索引值
  9. Debug.Log("loadedLevel:" + Application.loadedLevel);
  10. //返回当前场景的名字
  11. Debug.Log("loadedLevelName:" + Application.loadedLevelName);
  12. //是否有场景正在被加载
  13. Debug.Log("isLoadingLevel:" + Application.isLoadingLevel);
  14. //返回游戏中可被加载的场景数量
  15. Debug.Log("levelCount:" + Application.levelCount);
  16. //返回当前游戏的运行平台
  17. Debug.Log("platform:" + Application.platform);
  18. //当前游戏是否正在运行
  19. Debug.Log("isPlaying:" + Application.isPlaying);
  20. //当前游戏是否处于Unity编辑模式
  21. Debug.Log("isEditor:" + Application.isEditor);
  22. }
  23. }

LoadedLevel

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CaptureScreenshot_ts : MonoBehaviour
  5. {
  6. ;
  7. void Update()
  8. {
  9. )
  10. {
  11. //默认值,不放大
  12. Application.CaptureScreenshot();
  13. }
  14. )
  15. {
  16. //放大系数为1,即不放大
  17. Application.CaptureScreenshot();
  18. }
  19. else
  20. {
  21. //放大系数为2,即放大2倍
  22. Application.CaptureScreenshot();
  23. }
  24. tp++;
  25. }
  26. }

CaptureScreenshot

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Capture_Use_ts : MonoBehaviour
  5. {
  6.  
  7. //td:用来指向屏幕截图
  8. Texture2D td = null;
  9. //txt_bg:用来指向文本输入的背景图片
  10. //可以指向一张纯色的图片,也可以自定义一个纯色的背景
  11. //本程序自定义了一个纯色的背景
  12. Texture2D txt_bg;
  13. //txt_w和txt_h用来记录文本框的宽度和高度
  14. int txt_w, txt_h;
  15. //my_save_path:用来记录截图的保存路径
  16. string my_save_path = "";
  17. //show_txt:用来记录输入的文本
  18. string show_txt = "在此输入";
  19. //my_colors:用来记录文本输入框的纹理颜色
  20. Color[] my_colors;
  21. //_w和_h用来记录my_colors的宽度和高度
  22. int _w, _h;
  23. //step:用来记录当前状态,step共有3种状态:
  24. //step=0时,是等待状态,等待在文本框中输入文本
  25. //step=1时,即点击“确定”按钮后,生成截图并保存
  26. //step=2时,读取截图信息
  27. //step=3时,是对读取的截图信息进行有选择的提取,并生成想要展示的内容
  28. ;
  29. //go:用来指向拼字所用物体对象
  30. public GameObject go;
  31. //gos:用来记录所有的go对象
  32. GameObject[] gos;
  33. //gos_max用来记录gos的最大容量
  34. int gos_max;
  35. //gos_cur用来记录gos当前使用值
  36. ;
  37. //is_show:用来记录图像矩阵中某个点是否需要展示物体
  38. bool[,] is_show;
  39.  
  40. void Start()
  41. {
  42. //初始化文本框的宽度和高度
  43. txt_w = ;
  44. txt_h = ;
  45. //初始化截取区间的大小,为了避免边界识别错误,其值应该比文本框的宽度和高度少几个像素
  46. _w = txt_w;
  47. _h = txt_h;
  48. _w -= ;
  49. _h -= ;
  50. //自定义txt_bg纹理
  51. txt_bg = new Texture2D(txt_w, txt_h);
  52. Color[] tdc = new Color[txt_w * txt_h];
  53. ; i < txt_w * txt_h; i++)
  54. {
  55. //所用像素点颜色应相同
  56. tdc[i] = Color.white;
  57. }
  58. txt_bg.SetPixels(, , txt_w, txt_h, tdc);
  59.  
  60. is_show = new bool[_h, _w];
  61. //初始化gos_max,其值大小为_w * _h的三分之一在一般情况下就够用了
  62. gos_max = _w * _h / ;
  63. //实例化gos,使其随机分布_w和_h的区间内
  64. gos = new GameObject[gos_max];
  65. ; i < gos_max; i++)
  66. {
  67. gos[i] = (GameObject)Instantiate(go, new Vector3(Random.value * _w, Random.value * _h, 10.0f), Quaternion.identity);
  68. gos[i].GetComponent<Capture_Use_Sub_ts>().toward = gos[i].transform.position;
  69. }
  70. //存储初始界面截图
  71. my_save_path = Application.persistentDataPath;
  72. Application.CaptureScreenshot(my_save_path + "/ts02.png");
  73.  
  74. }
  75.  
  76. void Update()
  77. {
  78. switch (step)
  79. {
  80. :
  81. break;
  82. :
  83. step = ;
  84. //截图并保存
  85. my_save_path = Application.persistentDataPath;
  86. Application.CaptureScreenshot(my_save_path + "/ts02.png");
  87. //给电脑一点儿时间用来保存新截取的图片
  88. Invoke("My_WaitForSeconds", 0.4f);
  89. Debug.Log(my_save_path);
  90. break;
  91. :
  92. //由于在读取截图纹理的时候,一帧之内可能无法读完
  93. //所以需要step=0,避免逻辑出现混乱
  94. step = ;
  95. //读取截图信息
  96. my_save_path = Application.persistentDataPath;
  97. StartCoroutine(WaitLoad(my_save_path + "/ts02.png"));
  98. break;
  99. :
  100. //在计算并生成展示信息的时候,一帧之内可能无法完成
  101. //所以需要step=0,避免逻辑出现混乱
  102. step = ;
  103. //计算并生成展示信息
  104. Cum();
  105. break;
  106. }
  107. }
  108.  
  109. //计算并生成展示信息
  110. void Cum()
  111. {
  112. if (td != null)
  113. {
  114. float ft;
  115. //ft:用来记录文本框左下角像素的R通道值,用来作为后面的参照
  116. ft = td.GetPixel(, td.height - _h).r;
  117. //截取文本框纹理信息
  118. //需要注意的是,纹理坐标系和GUI坐标系不同
  119. //纹理坐标系以坐下角为原点,而GUI坐标系以左上角为原点
  120. //以2为x方向起点是为了避免截图边缘的痕迹
  121. my_colors = td.GetPixels(, td.height - _h, _w, _h);
  122. int l = my_colors.Length;
  123. Debug.Log("length: " + l);
  124. //通过遍历my_colors的R值,将其与ft比较来确定是否需要展示物体
  125. ; i < l; i++)
  126. {
  127. is_show[i / _w, i % _w] = my_colors[i].r == ft ? false : true;
  128. }
  129. //根据is_show的值排列gos中物体的位置
  130. ; i < _h; i++)
  131. {
  132. ; j < _w; j++)
  133. {
  134. if (is_show[i, j])
  135. {
  136. if (gos_cur < gos_max)
  137. {
  138. gos[gos_cur].GetComponent<Capture_Use_Sub_ts>().toward = new Vector3(j, i, 0.0f);
  139. gos[gos_cur].SetActive(true);
  140. gos_cur++;
  141. }
  142. //当当前gos数量不够用时需要扩充gos的容量
  143. else
  144. {
  145. Debug.Log("容量过小");
  146. int temps = gos_max;
  147. //将gos容量扩大1.5倍
  148. gos_max = (int)(gos_max * 1.5f);
  149. GameObject[] tps = new GameObject[gos_max];
  150. ; k < temps; k++)
  151. {
  152. tps[k] = gos[k];
  153. }
  154. for (int k = temps; k < gos_max; k++)
  155. {
  156. tps[k] = (GameObject)Instantiate(go, new Vector3(Random.value * _h, Random.value * _w, 10.0f), Quaternion.identity);
  157. tps[k].GetComponent<Capture_Use_Sub_ts>().toward = tps[k].transform.position;
  158. }
  159.  
  160. gos = new GameObject[gos_max];
  161. gos = tps;
  162.  
  163. gos[gos_cur].GetComponent<Capture_Use_Sub_ts>().toward = new Vector3(j, i, 0.0f);
  164. gos[gos_cur].SetActive(true);
  165. gos_cur++;
  166.  
  167. }
  168.  
  169. }
  170. }
  171. }
  172. //隐藏gos中未曾用到的物体
  173. for (int k = gos_cur; k < gos_max; k++)
  174. {
  175. gos[k].SetActive(false);
  176. }
  177. }
  178. }
  179. //绘制界面
  180. void OnGUI()
  181. {
  182. //绘制纹理作为TextField的背景
  183. GUI.DrawTexture(new Rect(0.0f, 0.0f, txt_w, txt_h), txt_bg);
  184. GUIStyle gs = new GUIStyle();
  185. gs.fontSize = ;
  186. show_txt = GUI.TextField(, gs);
  187.  
  188. , , , ), "确定"))
  189. {
  190. //取消在TextField中的焦点
  191. GUI.FocusControl(null);
  192. //重置gos_cur的值
  193. gos_cur = ;
  194. step = ;
  195. }
  196. //程序退出
  197. , , , ), "退出"))
  198. {
  199. Application.Quit();
  200. }
  201. }
  202.  
  203. //加载图片
  204. IEnumerator WaitLoad(string fileName)
  205. {
  206. WWW wwwTexture = new WWW("file://" + fileName);
  207. Debug.Log(wwwTexture.url);
  208. yield return wwwTexture;
  209. td = wwwTexture.texture;
  210. step = ;
  211. }
  212. //进入步骤2
  213. void My_WaitForSeconds()
  214. {
  215. step = ;
  216. }
  217. }

Capture_Use

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Capture_Use_Sub_ts : MonoBehaviour
  5. {
  6. //物体移动的目标位置
  7. public Vector3 toward;
  8. //物体移动时间
  9. float delays;
  10. void Start()
  11. {
  12. //获取一个随机值
  13. delays = Random.Range(2.0f, 4.0f);
  14. }
  15.  
  16. void Update()
  17. {
  18. //通过更改物体位置来达到物体运动的效果
  19. transform.position = Vector3.MoveTowards(transform.position, toward, delays);
  20. }
  21. }

Capture_Use_Sub

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RegisterLogCallback_ts : MonoBehaviour
  5. {
  6. string output = "";//日志输出信息
  7. string stack = "";//堆栈跟踪信息
  8. string logType = "";//日志类型
  9. ;
  10. //打印日志信息
  11. void Update()
  12. {
  13. Debug.Log("stack:" + stack);
  14. Debug.Log("logType:" + logType);
  15. Debug.Log("tp:"+(tp++));
  16. Debug.Log("output:" + output);
  17. }
  18. void OnEnable()
  19. {
  20. //注册委托
  21. Application.RegisterLogCallback(MyCallback);
  22. }
  23. void OnDisable()
  24. {
  25. //取消委托
  26. Application.RegisterLogCallback(null);
  27. }
  28. //委托方法
  29. //方法名字可以自定义,但方法的参数类型要符合Application.LogCallback中的参数类型
  30. void MyCallback(string logString, string stackTrace, LogType type)
  31. {
  32. output = logString;
  33. stack = stackTrace;
  34. logType = type.ToString();
  35. }
  36. }

RegisterLogCallback

2 Camera类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Aspect_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //camera.aspect的默认值即为当前硬件的aspect值
  9. Debug.Log("camera.aspect的默认值:" + camera.aspect);
  10. }
  11. void OnGUI()
  12. {
  13. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "aspect=1.0f"))
  14. {
  15. camera.ResetAspect();
  16. camera.aspect = 1.0f;
  17. }
  18. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "aspect=2.0f"))
  19. {
  20. camera.ResetAspect();
  21. camera.aspect = 2.0f;
  22. }
  23. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "aspect还原默认值"))
  24. {
  25. camera.ResetAspect();
  26. }
  27. }
  28. }

Aspect

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CameraToWorldMatrix_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Debug.Log("Camera旋转前位置:" + transform.position);
  9. Matrix4x4 m = camera.cameraToWorldMatrix;
  10. //v3的值为沿着Camera局部坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
  11. Vector3 v3 = m.MultiplyPoint(Vector3.forward * 5.0f);
  12. //v4的值为沿着Camera世界坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
  13. Vector3 v4 = m.MultiplyPoint(transform.forward * 5.0f);
  14. //打印v3、v4
  15. Debug.Log("旋转前,v3坐标值:" + v3);
  16. Debug.Log("旋转前,v4坐标值:" + v4);
  17. transform.Rotate(Vector3.up * 90.0f);
  18. Debug.Log("Camera旋转后位置:" + transform.position);
  19. m = camera.cameraToWorldMatrix;
  20. //v3的值为沿着Camera局部坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
  21. v3 = m.MultiplyPoint(Vector3.forward * 5.0f);
  22. //v3的值为沿着Camera世界坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
  23. v4 = m.MultiplyPoint(transform.forward * 5.0f);
  24. //打印v3、v4
  25. Debug.Log("旋转后,v3坐标值:" + v3);
  26. Debug.Log("旋转后,v4坐标值:" + v4);
  27. }
  28. }

CameraToWorldMatrix

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CullingMask_ts : MonoBehaviour
  5. {
  6. void OnGUI()
  7. {
  8. //默认CullingMask=-1,即渲染任何层
  9. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "CullingMask=-1"))
  10. {
  11. camera.cullingMask = -;
  12. }
  13. //不渲染任何层
  14. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "CullingMask=0"))
  15. {
  16. camera.cullingMask = ;
  17. }
  18. //仅渲染第0层
  19. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "CullingMask=1<<0"))
  20. {
  21. camera.cullingMask = << ;
  22. }
  23. //仅渲染第8层
  24. if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "CullingMask=1<<8"))
  25. {
  26. camera.cullingMask = << ;
  27. }
  28. //渲染第8层与第0层
  29. if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "CullingMask=0&&8"))
  30. {
  31. //注:不可大意写成camera.cullingMask = 1 << 8+1;或
  32. //camera.cullingMask = 1+1<<8 ;因为根据运算符优先次序其分别等价于:
  33. //camera.cullingMask = 1 << (8+1)和camera.cullingMask = (1+1)<<8;
  34. camera.cullingMask = ( << ) + ;
  35. }
  36.  
  37. }
  38. }

CullingMask

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EventMask_ts : MonoBehaviour
  5. {
  6. bool is_rotate = false;//控制物体旋转
  7. public Camera c;//指向场景中摄像机
  8. //记录摄像机的eventMask值,可以在程序运行时在Inspector面板中修改其值的大小
  9. ;
  10. //记录当前物体的层
  11. int layer_now;
  12. int tp;//记录2的layer次方的值
  13. int ad;//记录与运算(&)的结果
  14. string str = null;
  15.  
  16. void Update()
  17. {
  18. //记录当前对象的层,可以在程序运行时在Inspector面板中选择不同的层
  19. layer_now = gameObject.layer;
  20. //求2的layer_now次方的值
  21. tp = (int)Mathf.Pow(2.0f, layer_now);
  22. //与运算(&)
  23. ad = eventMask_now & tp;
  24. c.eventMask = eventMask_now;
  25. //当is_rotate为true时旋转物体
  26. if (is_rotate)
  27. {
  28. transform.Rotate(Vector3.up * 15.0f * Time.deltaTime);
  29. }
  30. }
  31. //当鼠标左键按下时,物体开始旋转
  32. void OnMouseDown()
  33. {
  34. is_rotate = true;
  35. }
  36. //当鼠标左键抬起时,物体结束旋转
  37. void OnMouseUp()
  38. {
  39. is_rotate = false;
  40. }
  41. void OnGUI()
  42. {
  43. GUI.Label(new Rect(10.0f, 10.0f, 300.0f, 45.0f), "当前对象的layer值为:" + layer_now + " , 2的layer次方的值为" + tp);
  44. GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前摄像机eventMask的值为:" + eventMask_now);
  45. GUI.Label(new Rect(10.0f, 110.0f, 500.0f, 45.0f), "根据算法,当eventMask的值与" + tp + "进行与运算(&)后, 若结果为" + tp + ",则物体相应OnMousexxx方法,否则不响应!");
  46.  
  47. if (ad == tp)
  48. {
  49. str = " ,所以物体会相应OnMouseXXX方法!";
  50. }
  51. else
  52. {
  53. str = " ,所以物体不会相应OnMouseXXX方法!";
  54. }
  55. GUI.Label(new Rect(10.0f, 160.0f, 500.0f, 45.0f), "而当前eventMask与" + tp + "进行与运算(&)的结果为" + ad + str);
  56. }
  57. }

EventMask

  1. using UnityEngine;
  2. using System.Collections;
  3. public class LayerCullDistances_ts : MonoBehaviour
  4. {
  5. public Transform cb1;
  6. void Start()
  7. {
  8. //定义大小为32的一维数组,用来存储所有层的剔除距离
  9. ];
  10. //设置第9层的剔除距离
  11. distances[] = Vector3.Distance(transform.position, cb1.position);
  12. //将数组赋给摄像机的layerCullDistances
  13. camera.layerCullDistances = distances;
  14. }
  15. void Update()
  16. {
  17. //摄像机远离物体
  18. transform.Translate(transform.right * Time.deltaTime);
  19. }
  20. }

LayerCullDistances

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class layerCullSpherical_ts : MonoBehaviour
  5. {
  6. public Transform cb1, cb2, cb3;
  7. void Start()
  8. {
  9. //定义大小为32的一维数组,用来存储所有层的剔除距离
  10. ];
  11. //设置第9层的剔除距离
  12. distances[] = Vector3.Distance(transform.position, cb1.position);
  13. //将数组赋给摄像机的layerCullDistances
  14. camera.layerCullDistances = distances;
  15. //打印出三个物体距离摄像机的距离
  16. Debug.Log("Cube1距离摄像机的距离:" + Vector3.Distance(transform.position, cb1.position));
  17. Debug.Log("Cube2距离摄像机的距离:" + Vector3.Distance(transform.position, cb2.position));
  18. Debug.Log("Cube3距离摄像机的距离:" + Vector3.Distance(transform.position, cb3.position));
  19. }
  20.  
  21. void OnGUI()
  22. {
  23. //使用球形距离剔除
  24. if (GUI.Button(new Rect(10.0f, 10.0f, 180.0f, 45.0f), "use layerCullSpherical"))
  25. {
  26. camera.layerCullSpherical = true;
  27. }
  28. //取消球形距离剔除
  29. if (GUI.Button(new Rect(10.0f, 60.0f, 180.0f, 45.0f), "unuse layerCullSpherical"))
  30. {
  31. camera.layerCullSpherical = false;
  32. }
  33. }
  34. }

layerCullSpherical

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class orthographic_ts : MonoBehaviour
  5. {
  6. float len = 5.5f;
  7. void OnGUI()
  8. {
  9. if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "正交投影"))
  10. {
  11. camera.orthographic = true;
  12. len = 5.5f;
  13. }
  14. if (GUI.Button(new Rect(150.0f, 10.0f, 120.0f, 45.0f), "透视投影"))
  15. {
  16. camera.orthographic = false;
  17. len = 60.0f;
  18. }
  19. if (camera.orthographic)
  20. {
  21. //正交投影模式下,物体没有远大近小的效果,
  22. //orthographicSize的大小无限制,当orthographicSize为负数时视口的内容会颠倒,
  23. //orthographicSize的绝对值为摄像机视口的高度值,即上下两条边之间的距离
  24. len = GUI.HorizontalSlider(new Rect(10.0f, 60.0f, 300.0f, 45.0f), len, -20.0f, 20.0f);
  25. camera.orthographicSize = len;
  26. }
  27. else
  28. {
  29. //透视投影模式下,物体有远大近小的效果,
  30. //fieldOfViewd的取值范围为1.0-179.0
  31. len = GUI.HorizontalSlider(new Rect(10.0f, 60.0f, 300.0f, 45.0f), len, 1.0f, 179.0f);
  32. camera.fieldOfView = len;
  33. }
  34. //实时显示len大小
  35. GUI.Label(new Rect(320.0f, 60.0f, 120.0f, 45.0f), len.ToString());
  36. }
  37. }

orthographic

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class PixelRect_ts : MonoBehaviour
  5. {
  6. ;
  7. float temp_x = 0.0f, temp_y = 0.0f;
  8. void Update()
  9. {
  10. //Screen.width和Screen.height为模拟硬件屏幕的宽高值,
  11. //其返回值不随camera.pixelWidth和camera.pixelHeight的改变而改变
  12. Debug.Log("Screen.width:" + Screen.width);
  13. Debug.Log("Screen.height:" + Screen.height);
  14. Debug.Log("pixelWidth:" + camera.pixelWidth);
  15. Debug.Log("pixelHeight:" + camera.pixelHeight);
  16. //通过改变Camera的坐标位置而改变视口的区间
  17. )
  18. {
  19. if (camera.pixelWidth > 1.0f)
  20. {
  21. temp_x += Time.deltaTime * 20.0f;
  22. }
  23. //取消以下注释察看平移状况
  24. //if (camera.pixelHeight > 1.0f)
  25. //{
  26. // temp_y += Time.deltaTime * 20.0f;
  27. //}
  28. camera.pixelRect = new Rect(temp_x, temp_y, camera.pixelWidth, camera.pixelHeight);
  29. }
  30. //通过改变Camera的视口宽度和高度来改变视口的区间
  31. )
  32. {
  33. if (camera.pixelWidth > 1.0f)
  34. {
  35. temp_x = camera.pixelWidth - Time.deltaTime * 20.0f;
  36. }
  37. //取消以下注释察看平移状况
  38. //if (camera.pixelHeight > 1.0f)
  39. //{
  40. // temp_y = camera.pixelHeight - Time.deltaTime * 20.0f;
  41. //}
  42. camera.pixelRect = , , temp_x, temp_y);
  43. }
  44. }
  45. void OnGUI()
  46. {
  47. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "视口改变方式1"))
  48. {
  49. camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  50. which_change = ;
  51. temp_x = 0.0f;
  52. temp_y = 0.0f;
  53. }
  54. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "视口改变方式2"))
  55. {
  56. camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  57. which_change = ;
  58. temp_x = 0.0f;
  59. temp_y = camera.pixelHeight;
  60. }
  61. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "视口还原"))
  62. {
  63. camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  64. which_change = -;
  65. }
  66. }
  67. }

PixelRect

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ProjectionMatrix_ts : MonoBehaviour
  5. {
  6. public Transform sp, cb;
  7. public Matrix4x4 originalProjection;
  8. float q=0.1f;//晃动振幅
  9. float p=1.5f;//晃动频率
  10. ;
  11. void Start()
  12. {
  13. //记录原始投影矩阵
  14. originalProjection = camera.projectionMatrix;
  15. }
  16. void Update()
  17. {
  18. sp.RotateAround(cb.position, cb.up, 45.0f * Time.deltaTime);
  19. Matrix4x4 pr = originalProjection;
  20. switch (which_change)
  21. {
  22. :
  23. break;
  24. :
  25. //绕摄像机X轴晃动
  26. pr.m11 += Mathf.Sin(Time.time * p) * q;
  27. break;
  28. :
  29. //绕摄像机Y轴晃动
  30. pr.m01 += Mathf.Sin(Time.time * p) * q;
  31. break;
  32. :
  33. //绕摄像机Z轴晃动
  34. pr.m10 += Mathf.Sin(Time.time * p) * q;
  35. break;
  36. :
  37. //绕摄像机左右移动
  38. pr.m02 += Mathf.Sin(Time.time * p) * q;
  39. break;
  40. :
  41. //摄像机视口放缩运动
  42. pr.m00 += Mathf.Sin(Time.time * p) * q;
  43. break;
  44. }
  45. //设置Camera的变换矩阵
  46. camera.projectionMatrix = pr;
  47. }
  48. void OnGUI()
  49. {
  50. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "绕摄像机X轴晃动"))
  51. {
  52. camera.ResetProjectionMatrix();
  53. which_change = ;
  54. }
  55. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "绕摄像机Y轴晃动"))
  56. {
  57. camera.ResetProjectionMatrix();
  58. which_change = ;
  59. }
  60. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "绕摄像机Z轴晃动"))
  61. {
  62. camera.ResetProjectionMatrix();
  63. which_change = ;
  64. }
  65. if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "绕摄像机左右移动"))
  66. {
  67. camera.ResetProjectionMatrix();
  68. which_change = ;
  69. }
  70. if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "视口放缩运动"))
  71. {
  72. camera.ResetProjectionMatrix();
  73. which_change = ;
  74. }
  75. }
  76. }

ProjectionMatrix

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Rect_ts : MonoBehaviour
  5. {
  6. ;
  7. float temp_x = 0.0f, temp_y = 0.0f;
  8. void Update()
  9. {
  10. //视口平移
  11. )
  12. {
  13. if (camera.rect.x < 1.0f)
  14. {
  15. //沿着X轴平移
  16. temp_x = camera.rect.x + Time.deltaTime * 0.2f;
  17. }
  18. //取消下面注释察看平移的变化
  19. //if (camera.rect.y< 1.0f)
  20. //{
  21. //沿着Y轴平移
  22. // temp_y = camera.rect.y + Time.deltaTime * 0.2f;
  23. //}
  24. camera.rect = new Rect(temp_x, temp_y, camera.rect.width, camera.rect.height);
  25. }
  26. //视口放缩
  27. )
  28. {
  29. if (camera.rect.width > 0.0f)
  30. {
  31. //沿着X轴放缩
  32. temp_x = camera.rect.width - Time.deltaTime * 0.2f;
  33. }
  34. if (camera.rect.height > 0.0f)
  35. {
  36. //沿着Y轴放缩
  37. temp_y = camera.rect.height - Time.deltaTime * 0.2f;
  38. }
  39. camera.rect = new Rect(camera.rect.x, camera.rect.y, temp_x, temp_y);
  40. }
  41. }
  42. void OnGUI()
  43. {
  44. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "视口平移"))
  45. {
  46. //重置视口
  47. camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  48. which_change = ;
  49. temp_y = 0.0f;
  50. }
  51. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "视口放缩"))
  52. {
  53. camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  54. which_change = ;
  55. }
  56. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "视口还原"))
  57. {
  58. camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
  59. which_change = -;
  60. }
  61. }
  62. }

Rect

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class renderingPath_ts : MonoBehaviour
  5. {
  6. void OnGUI()
  7. {
  8. if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "UsePlayerSettings"))
  9. {
  10. camera.renderingPath = RenderingPath.UsePlayerSettings;
  11. }
  12. if (GUI.Button(new Rect(10.0f, 60.0f, 120.0f, 45.0f), "VertexLit"))
  13. {
  14. camera.renderingPath = RenderingPath.VertexLit;
  15. }
  16. if (GUI.Button(new Rect(10.0f, 110.0f, 120.0f, 45.0f), "Forward"))
  17. {
  18. camera.renderingPath = RenderingPath.Forward;
  19. }
  20. if (GUI.Button(new Rect(10.0f, 160.0f, 120.0f, 45.0f), "DeferredLighting"))
  21. {
  22. camera.renderingPath = RenderingPath.DeferredLighting;
  23. }
  24. }
  25. }

renderingPath

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Target_ts : MonoBehaviour {
  5. public Transform ts;
  6. void Update () {
  7. transform.RotateAround(ts.position,ts.up,30.0f*Time.deltaTime);
  8. }
  9. }

Target

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class WorldToCameraMatrix_ts : MonoBehaviour
  5. {
  6. public Camera c_test;
  7. void OnGUI()
  8. {
  9. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "更改变换矩阵"))
  10. {
  11. //使用c_test的变换矩阵
  12. camera.worldToCameraMatrix = c_test.worldToCameraMatrix;
  13. //也可使用如下代码实现同样功能
  14. // camera.CopyFrom(c_test);
  15. }
  16. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "重置变换矩阵"))
  17. {
  18. camera.ResetWorldToCameraMatrix();
  19. }
  20. }
  21. }

WorldToCameraMatrix

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RenderToCubemap_ts : MonoBehaviour
  5. {
  6. public Cubemap cp;
  7. void Start()
  8. {
  9. camera.RenderToCubemap(cp);
  10. }
  11. }

RenderToCubemap

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RenderWithShader_ts : MonoBehaviour
  5. {
  6. bool is_use = false;
  7. void OnGUI()
  8. {
  9. if (is_use)
  10. {
  11. //使用高光shader:Specular来渲染Camera
  12. camera.RenderWithShader(Shader.Find("Specular"), "RenderType");
  13. }
  14. if (GUI.Button(new Rect(10.0f, 10.0f, 300.0f, 45.0f), "使用RenderWithShader启用高光"))
  15. {
  16. //RenderWithShader每调用一次只渲染一帧,所以不可将其直接放到这儿
  17. //camera.RenderWithShader(Shader.Find("Specular"), "RenderType");
  18. is_use = true;
  19. }
  20. if (GUI.Button(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "使用SetReplacementShader启用高光"))
  21. {
  22. //SetReplacementShader方法用来替换已有shader,调用一次即可
  23. camera.SetReplacementShader(Shader.Find("Specular"), "RenderType");
  24. is_use = false;
  25. }
  26. if (GUI.Button(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "关闭高光"))
  27. {
  28. camera.ResetReplacementShader();
  29. is_use = false;
  30. }
  31. }
  32. }

RenderWithShader

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ScreenPointToRay_ts : MonoBehaviour
  5. {
  6. Ray ray;
  7. RaycastHit hit;
  8. Vector3 v3 = new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 0.0f);
  9. Vector3 hitpoint = Vector3.zero;
  10. void Update()
  11. {
  12. //射线沿着屏幕X轴从左向右循环扫描
  13. v3.x = v3.x >= Screen.width ? 0.0f : v3.x + 1.0f;
  14. //生成射线
  15. ray = camera.ScreenPointToRay(v3);
  16. if (Physics.Raycast(ray, out hit, 100.0f))
  17. {
  18. //绘制线,在Scene视图中可见
  19. Debug.DrawLine(ray.origin, hit.point, Color.green);
  20. //输出射线探测到的物体的名称
  21. Debug.Log("射线探测到的物体名称:" + hit.transform.name);
  22. }
  23. }
  24. }

ScreenPointToRay

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ScreenToViewportPoint_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. transform.position = new Vector3(0.0f, 0.0f, 1.0f);
  9. transform.rotation = Quaternion.identity;
  10. //从屏幕的实际坐标点向视口的单位化比例值转换
  11. Debug.Log("1:" + camera.ScreenToViewportPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f)));
  12. //从视口的单位化比例值向屏幕的实际坐标点转换
  13. Debug.Log("2:" + camera.ViewportToScreenPoint(new Vector3(0.5f, 0.5f, 100.0f)));
  14. Debug.Log("屏幕宽:" + Screen.width + " 屏幕高:" + Screen.height);
  15. }
  16. }

ScreenToViewportPoint

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ScreenToWorldPoint_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. transform.position = new Vector3(0.0f, 0.0f, 1.0f);
  9. camera.fieldOfView = 60.0f;
  10. camera.aspect = 16.0f / 10.0f;
  11. //Z轴前方100处对应的屏幕的左下角的世界坐标值
  12. Debug.Log("1:" + camera.ScreenToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f)));
  13. //Z轴前方100处对应的屏幕的中间的世界坐标值
  14. Debug.Log("2:" + camera.ScreenToWorldPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f)));
  15. //Z轴前方100处对应的屏幕的右上角的世界坐标值
  16. Debug.Log("3:" + camera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 100.0f)));
  17. }
  18. }

ScreenToWorldPoint

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SetTargetBuffers_ts : MonoBehaviour
  5. {
  6. //声明两个RendererTexture变量
  7. public RenderTexture RT_1, RT_2;
  8. public Camera c;//指定Camera
  9.  
  10. void OnGUI()
  11. {
  12. //设置RT_1的buffer为摄像机c的渲染
  13. if (GUI.Button(new Rect(10.0f, 10.0f, 180.0f, 45.0f), "set target buffers"))
  14. {
  15. c.SetTargetBuffers(RT_1.colorBuffer, RT_1.depthBuffer);
  16. }
  17. //设置RT_2的buffer为摄像机c的渲染,此时RT_1的buffer变为场景中Camera1的渲染
  18. if (GUI.Button(new Rect(10.0f, 60.0f, 180.0f, 45.0f), "Reset target buffers"))
  19. {
  20. c.SetTargetBuffers(RT_2.colorBuffer, RT_2.depthBuffer);
  21. }
  22. }
  23. }

SetTargetBuffers

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ViewportPointToRay_ts : MonoBehaviour
  5. {
  6. Ray ray;//射线
  7. RaycastHit hit;
  8. Vector3 v3 = new Vector3(0.5f, 0.5f, 0.0f);
  9. Vector3 hitpoint = Vector3.zero;
  10. void Update()
  11. {
  12. //射线沿着屏幕X轴从左向右循环扫描
  13. v3.x = v3.x >= 1.0f ? 0.0f : v3.x + 0.002f;
  14. //生成射线
  15. ray = camera.ViewportPointToRay(v3);
  16. if (Physics.Raycast(ray, out hit, 100.0f))
  17. {
  18. //绘制线,在Scene视图中可见
  19. Debug.DrawLine(ray.origin, hit.point, Color.green);
  20. //输出射线探测到的物体的名称
  21. Debug.Log("射线探测到的物体名称:" + hit.transform.name);
  22. }
  23. }
  24. }

ViewportPointToRay

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ViewportToWorldPoint_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. transform.position = new Vector3(1.0f, 0.0f, 1.0f);
  9. camera.fieldOfView = 60.0f;
  10. camera.aspect = 16.0f / 10.0f;
  11. //屏幕左下角
  12. Debug.Log("1:" + camera.ViewportToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f)));
  13. //屏幕中间
  14. Debug.Log("2:" + camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 100.0f)));
  15. //屏幕右上角
  16. Debug.Log("3:" + camera.ViewportToWorldPoint(new Vector3(1.0f, 1.0f, 100.0f)));
  17. }
  18. }

ViewportToWorldPoint

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class WorldToScreenPoint_ts : MonoBehaviour
  5. {
  6. public Transform cb, sp;
  7. public Texture2D t2;
  8. Vector3 v3 = Vector3.zero;
  9. float sg;
  10. void Start()
  11. {
  12. //记录屏幕高度
  13. sg = Screen.height;
  14. }
  15. void Update()
  16. {
  17. //sp绕着cb的Y轴旋转
  18. sp.RotateAround(cb.position, cb.up, 30.0f * Time.deltaTime);
  19. //获取sp在屏幕上的坐标点
  20. v3 = camera.WorldToScreenPoint(sp.position);
  21. }
  22. void OnGUI()
  23. {
  24. //绘制纹理
  25. GUI.DrawTexture(new Rect(0.0f, sg - v3.y, v3.x, sg), t2);
  26. }
  27. }

WorldToScreenPoint

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class WorldToViewportPoint_ts : MonoBehaviour
  5. {
  6. public Transform cb, sp;
  7. public Texture2D t2;
  8. Vector3 v3 = Vector3.zero;
  9. float sw, sh;
  10. void Start()
  11. {
  12. //记录屏幕的宽度和高度
  13. sw = Screen.width;
  14. sh = Screen.height;
  15. }
  16. void Update()
  17. {
  18. //物体sp始终绕cb的Y轴旋转
  19. sp.RotateAround(cb.position, cb.up, 30.0f * Time.deltaTime);
  20. //记录sp映射到屏幕上的比例值
  21. v3 = camera.WorldToViewportPoint(sp.position);
  22. }
  23. void OnGUI()
  24. {
  25. //绘制纹理,由于方法WorldToViewportPoint的返回值的y分量是从屏幕下方向上方递增的,
  26. //所以需要先计算1.0f - v3.y的值,然后再和sh相乘。
  27. GUI.DrawTexture(new Rect(0.0f, sh * (1.0f - v3.y), sw * v3.x, sh), t2);
  28. }
  29. }

WorldToViewportPoint

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Compare_ts : MonoBehaviour
  5. {
  6. Vector3 v1;
  7. void Start()
  8. {
  9. v1 = transform.position;
  10. }
  11. void OnGUI()
  12. {
  13. //设置Camera视口宽高比例为2:1,点击此按钮后更改Game视图中不同的aspect值,
  14. //尽管Scene视图中Camera视口的宽高比会跟着改变,但实际Camera视口的内容依然是按照2:1
  15. //的比例所所获取的,不同的屏幕显示相同的内容会发生变形。
  16. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Camera视口宽高比例2:1"))
  17. {
  18. camera.aspect = 2.0f;
  19. transform.position = v1;
  20. }
  21. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Camera视口宽高比例1:2"))
  22. {
  23. camera.aspect = 0.5f;
  24. //更改Camera坐标,使被拉伸后的物体显示出来
  25. transform.position = new Vector3(v1.x, v1.y, 333.2f);
  26. }
  27. //恢复aspect的默认设置,即屏幕比例和Camera视口比例保持一致
  28. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "使用Game面板中aspect的选择"))
  29. {
  30. camera.ResetAspect();
  31. transform.position = v1;
  32. }
  33. }
  34. }

Compare

3 GameObject类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ActiveSelf_ts : MonoBehaviour {
  5. public GameObject cube1, cube2, cube3;
  6. void Start () {
  7. //对cube2设置为false,其他设置为true
  8. cube1.SetActive(true);
  9. cube2.SetActive(false);
  10. cube3.SetActive(true);
  11.  
  12. Debug.Log("activeSelf:");
  13. //尽管cube2被设置为false,但其子类cube3的activeSelf返回值仍然为true
  14. Debug.Log("cube1.activeSelf:" + cube1.activeSelf);
  15. Debug.Log("cube2.activeSelf:" + cube2.activeSelf);
  16. Debug.Log("cube3.activeSelf:" + cube3.activeSelf);
  17.  
  18. Debug.Log("\nactiveInHierarchy:");
  19. //cube2和cube3的activeInHierarchy返回值都为false。
  20. Debug.Log("cube1.activeInHierarchy:" + cube1.activeInHierarchy);
  21. Debug.Log("cube2.activeInHierarchy:" + cube2.activeInHierarchy);
  22. Debug.Log("cube3.activeInHierarchy:" + cube3.activeInHierarchy);
  23. }
  24. }

ActiveSelf

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Constructors_ts : MonoBehaviour {
  5. void Start () {
  6. //使用构造函数GameObject (name : String)
  7. GameObject g1 = new GameObject("G1");
  8. g1.AddComponent<Rigidbody>();
  9. //使用构造函数GameObject ()
  10. GameObject g2 = new GameObject();
  11. g2.AddComponent<FixedJoint>();
  12. //使用构造函数GameObject (name : String, params components : Type[])
  13. GameObject g3 = new GameObject("G3",typeof(MeshRenderer),typeof(Rigidbody),typeof(SpringJoint));
  14.  
  15. Debug.Log("g1 name:" + g1.name + "\nPosition:" + g1.transform.position);
  16. Debug.Log("g2 name:" + g2.name + "\nPosition:" + g2.transform.position);
  17. Debug.Log("g3 name:" + g3.name + "\nPosition:" + g3.transform.position);
  18. }
  19. }

Constructors

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GetComponent_ts : MonoBehaviour {
  5. void Start () {
  6. Debug.Log("以下是GetComponent的相关使用代码。\nGetComponent方法用来获取当前GameObject中符合Type类型的第一个组件。");
  7. //GetComponent (type : Type)
  8. Rigidbody rb = GetComponent(typeof(Rigidbody))as Rigidbody;
  9. Debug.Log("使用GetComponent (type : Type)获取Rigidbody:" + rb.GetInstanceID());
  10.  
  11. //GetComponent.<T>()
  12. rb=GetComponent<Rigidbody>();
  13. Debug.Log("使用GetComponent.<T>()获取Rigidbody:" + rb.GetInstanceID());
  14.  
  15. //GetComponent (type : String)
  16. rb = GetComponent("Rigidbody") as Rigidbody;
  17. Debug.Log("使用GetComponent (type : String)获取Rigidbody:" + rb.GetInstanceID());
  18.  
  19. Debug.Log("以下是GetComponentInChildren的相关使用代码。\nGetComponentInChildren方法用来获取当前GameObject的所有子类中中符合Type类型的第一个组件。");
  20.  
  21. //GetComponentInChildren (type : Type)
  22. rb = GetComponentInChildren(typeof(Rigidbody)) as Rigidbody;
  23. Debug.Log("使用GetComponentInChildren (type : Type)获取Rigidbody:" + rb.name);
  24.  
  25. //GetComponentInChildren.<T> ()
  26. rb=GetComponentInChildren<Rigidbody>();
  27. Debug.Log("使用GetComponentInChildren.<T>()获取Rigidbody:" + rb.name);
  28.  
  29. Debug.Log("以下是GetComponents的相关使用代码。\nGetComponents方法用来获取当前GameObject中符合Type类型的所有组件。");
  30.  
  31. //GetComponents (type : Type)
  32. Component[] cjs = GetComponents(typeof(ConfigurableJoint)) as Component[];
  33. foreach(ConfigurableJoint cj in cjs){
  34. Debug.Log("使用GetComponents (type : Type)获取ConfigurableJoint:" + cj.GetInstanceID());
  35. }
  36.  
  37. //GetComponents.<T> ()
  38. cjs = GetComponents<ConfigurableJoint>();
  39. foreach (ConfigurableJoint cj in cjs)
  40. {
  41. Debug.Log("使用GetComponents.<T>()获取ConfigurableJoint:" + cj.GetInstanceID());
  42. }
  43.  
  44. Debug.Log("以下是GetComponentsInChildren的相关使用代码。\nGetComponentsInChildren方法用来获取当前GameObject的子类中符合Type类型的所有组件。");
  45.  
  46. //GetComponentsInChildren(type: Type, includeInactive: boolean = false)
  47. cjs = GetComponentsInChildren(typeof(ConfigurableJoint), false) as Component[];
  48. foreach (ConfigurableJoint cj in cjs)
  49. {
  50. Debug.Log("使用GetComponentsInChildren(type: Type, false)获取ConfigurableJoint:" + cj.name);
  51. }
  52.  
  53. cjs = GetComponentsInChildren(typeof(ConfigurableJoint), true) as Component[];
  54. foreach (ConfigurableJoint cj in cjs)
  55. {
  56. Debug.Log("使用GetComponentsInChildren(type: Type, true)获取ConfigurableJoint:" + cj.name);
  57. }
  58.  
  59. //GetComponentsInChildren.<T> (includeInactive : boolean)
  60. cjs = GetComponentsInChildren<ConfigurableJoint>(true);
  61. foreach (ConfigurableJoint cj in cjs)
  62. {
  63. Debug.Log("使用GetComponentsInChildren.<T>(includeInactive : boolean)获取ConfigurableJoint:" + cj.name);
  64. }
  65.  
  66. //GetComponentsInChildren.<T> ()
  67. cjs = GetComponentsInChildren<ConfigurableJoint>();
  68. foreach (ConfigurableJoint cj in cjs)
  69. {
  70. Debug.Log("使用GetComponentsInChildren.<T>()获取ConfigurableJoint:" + cj.name);
  71. }
  72. }
  73. }

GetComponent

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SendMessage_ts : MonoBehaviour {
  5. void Start () {
  6. //向子类及自己发送信息
  7. //gameObject.BroadcastMessage("GetParentMessage",gameObject.name+":use BroadcastMessage send!");
  8. //向自己发送信息
  9. gameObject.SendMessage("GetSelfMessage",gameObject.name+":use SendMessage send!");
  10. ////向父类及自己发送信息
  11. //gameObject.SendMessageUpwards("GetChildrenMessage",gameObject.name+":use SendMessageUpwards send!");
  12. }
  13. //一个接受父类发送信息的方法
  14. private void GetParentMessage(string str){
  15. Debug.Log(gameObject.name + "收到父类发送的消息:" + str);
  16. }
  17. //一个接受自身发送信息的方法
  18. private void GetSelfMessage(string str)
  19. {
  20. Debug.Log(gameObject.name + "收到自身发送的消息:" + str);
  21. }
  22. //一个接受子类发送信息的方法
  23. private void GetChildrenMessage(string str)
  24. {
  25. Debug.Log(gameObject.name + "收到子类发送的消息:" + str);
  26. }
  27. }

SendMessage

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CreatePrimitive_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //使用GameObject.CreatePrimitive方法创建GameObject
  9. GameObject g1 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  10. g1.name = "G1";
  11. g1.tag = "sphere_Tag";
  12. //使用 AddComponent (className : String)方法添加组件
  13. g1.AddComponent("SpringJoint");
  14. //使用AddComponent (componentType : Type)方法添加组件
  15. g1.AddComponent(typeof(GUITexture));
  16. g1.transform.position = Vector3.zero;
  17.  
  18. GameObject g2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  19. g2.name = "G2";
  20. g2.tag = "sphere_Tag";
  21. //使用AddComponent.<T>()方法添加组件
  22. g2.AddComponent<Rigidbody>();
  23. g2.transform.position = 2.0f * Vector3.right;
  24. g2.GetComponent<Rigidbody>().useGravity = false;
  25.  
  26. GameObject g3 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
  27. g3.name = "G1";
  28. g3.tag = "sphere_Tag";
  29. g3.transform.position = 4.0f * Vector3.right;
  30.  
  31. //使用GameObject.Find类方法获取GameObject,返回符合条件的第一个对象
  32. Debug.Log("use Find:" + GameObject.Find("G1").transform.position);
  33. //使用GameObject.FindGameObjectWithTag类方法获取GameObject,返回符合条件的第一个对象
  34. Debug.Log("use FindGameObjectWithTag:" + GameObject.FindGameObjectWithTag("sphere_Tag").transform.position);
  35. //使用GameObject.FindGameObjectsWithTag类方法获取GameObject,返回符合条件的所有对象
  36. GameObject[] gos = GameObject.FindGameObjectsWithTag("sphere_Tag");
  37. foreach (GameObject go in gos)
  38. {
  39. Debug.Log("use FindGameObjectsWithTag:" + go.name + ":" + go.transform.position);
  40. }
  41.  
  42. g3.transform.parent = g2.transform;
  43. g2.transform.parent = g1.transform;
  44.  
  45. Debug.Log("use Find again1:" + GameObject.Find("G1").transform.position);
  46. //使用带"/"限定条件的方式查找GameObject,
  47. //此处返回的对象需其父类为G2,且G2的父类名为G1,
  48. //注意与上面不带"/"限定条件返回的对象的区别。
  49. Debug.Log("use Find again2:" + GameObject.Find("/G1/G2/G1").transform.position);
  50. }
  51. }

CreatePrimitive

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class BroadcastMessage_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. gameObject.BroadcastMessage("GetParentMessage", gameObject.name + ":use BroadcastMessage send!");
  9. }
  10. private void GetParentMessage(string str)
  11. {
  12. Debug.Log(gameObject.name + "收到父类发送的消息:" + str);
  13. }
  14.  
  15. private void GetSelfMessage(string str)
  16. {
  17. Debug.Log(gameObject.name + "收到自身发送的消息:" + str);
  18. }
  19.  
  20. private void GetChildrenMessage(string str)
  21. {
  22. Debug.Log(gameObject.name + "收到子类发送的消息:" + str);
  23. }
  24. }

BroadcastMessage

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GameObjectAndComponent_ts : MonoBehaviour {
  5. public GameObject sp;
  6. void Start () {
  7. //以下三种表达方式功能一样,都返回当前脚本所在GameObject对象中的Rigidbody组件
  8. Rigidbody rb1 = rigidbody;
  9. Rigidbody rb2 = GetComponent<Rigidbody>();
  10. Rigidbody rb3 = rigidbody.GetComponent<Rigidbody>();
  11. Debug.Log("rb1的InstanceID:" + rb1.GetInstanceID());
  12. Debug.Log("rb2的InstanceID:" + rb2.GetInstanceID());
  13. Debug.Log("rb3的InstanceID:" + rb3.GetInstanceID());
  14.  
  15. //使用前置引用获取引用对象的Rigidbody组件
  16. Debug.Log("前置引用sp对象中Rigidbody的InstanceID:"+sp.GetComponent<Rigidbody>().GetInstanceID());
  17. }
  18. }

GameObjectAndComponent

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SendMessageUpward_ts : MonoBehaviour {
  5. void Start () {
  6. gameObject.SendMessageUpwards("GetChildrenMessage", gameObject.name + ":use SendMessageUpwards send!");
  7. }
  8. private void GetParentMessage(string str)
  9. {
  10. Debug.Log(gameObject.name + "收到父类发送的消息:" + str);
  11. }
  12.  
  13. private void GetSelfMessage(string str)
  14. {
  15. Debug.Log(gameObject.name + "收到自身发送的消息:" + str);
  16. }
  17.  
  18. private void GetChildrenMessage(string str)
  19. {
  20. Debug.Log(gameObject.name + "收到子类发送的消息:" + str);
  21. }
  22. }

SendMessageUpward

4 HideFlags类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class DontSave_ts : MonoBehaviour {
  5. public GameObject go;
  6. public Transform t;
  7. void Start()
  8. {
  9. //GameObject对象使用HideFlags.DontSave可以在新scene中被保留
  10. go.hideFlags = HideFlags.DontSave;
  11. GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
  12. Pl.hideFlags = HideFlags.DontSave;
  13. //不可以对GameObject的组件设置HideFlags.DontSave,否则无效
  14. Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
  15. tf.hideFlags = HideFlags.DontSave;
  16. //导入名为newScene_unity的新scene
  17. Application.LoadLevel("newScene2_unity");
  18. }
  19. }

DontSave

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class HideInHierarchy_ts : MonoBehaviour
  5. {
  6. public GameObject go, sub;
  7. public Transform t;
  8. void Awake()
  9. {
  10. //go、sub、gameObject为已存在对象,需在Awake方法中使用HideFlags.HideInHierarchy
  11. go.hideFlags = HideFlags.HideInHierarchy;
  12. sub.hideFlags = HideFlags.HideInHierarchy;
  13. gameObject.hideFlags = HideFlags.HideInHierarchy;
  14. }
  15.  
  16. void Start()
  17. {
  18. //Pl、tf是在代码中创建的对象,可以在任何方法中使用HideFlags.HideInHierarchy
  19. GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
  20. Pl.hideFlags = HideFlags.HideInHierarchy;
  21. Transform tf = Instantiate(t, go.transform.position + , 0.0f, 0.0f), Quaternion.identity) as Transform;
  22. tf.hideFlags = HideFlags.HideInHierarchy;
  23. }
  24. }

HideInHierarchy

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class HideInInspector_td : MonoBehaviour {
  5. public GameObject go;
  6. public Transform t;
  7. void Start()
  8. {
  9. //go、gameObject、Pl都是GameObject对象,使用HideFlags.HideInInspector后,
  10. //其所有组件将在Inspector面板中隐藏,
  11. //但并不影响其子类在Inspector面板中的显示。
  12. go.hideFlags = HideFlags.HideInInspector;
  13. gameObject.hideFlags = HideFlags.HideInInspector;
  14. GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
  15. Pl.hideFlags = HideFlags.HideInInspector;
  16. //tf为Transform对象,使用HideFlags.HideInInspector后,
  17. //tf对应的GameObject的Transform组件将在Inspector面板中隐藏,
  18. //但GameObject的其他组件扔可在Inspector面板中显示。
  19. Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
  20. tf.hideFlags = HideFlags.HideInInspector;
  21. }
  22. }

HideInInspector

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class NewScene_ts : MonoBehaviour {
  5. void Start () {
  6. Debug.Log("这是NewScene!");
  7. //导入名为newScene_unity2的新scene
  8. Application.LoadLevel("newScene2_unity");
  9. }
  10. }

NewScene

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class NewScene2_ts : MonoBehaviour
  5. {
  6. GameObject cube, plane;
  7. void Start()
  8. {
  9. Debug.Log("这是NewScene2!");
  10. }
  11. //当程序退出时用DestroyImmediate()销毁被HideFlags.DontSave标识的对象,
  12. //否则即使程序已经退出,被HideFlags.DontSave标识的对象依然在Hierarchy面板中,
  13. //即每运行一次程序就会产生多余对象,造成内存泄漏。
  14. void OnApplicationQuit()
  15. {
  16. cube = GameObject.Find("Cube0");
  17. plane = GameObject.Find("Plane");
  18. if (cube)
  19. {
  20. Debug.Log("Cube0 DestroyImmediate");
  21. DestroyImmediate(cube);
  22. }
  23. if (plane)
  24. {
  25. Debug.Log("Plane DestroyImmediate");
  26. DestroyImmediate(plane);
  27. }
  28. }
  29. }

NewScene2

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class NotEditable_ts : MonoBehaviour {
  5. public GameObject go;
  6. public Transform t;
  7. void Start()
  8. {
  9. //GameObject对象使用HideFlags.NotEditable可以使得GameObject的
  10. //所有组件在Inspector面板中都处于不可编辑状态。
  11. //GameObject对象被HideFlags.NotEditable标识并不影响其子类的可编辑性。
  12. go.hideFlags = HideFlags.NotEditable;
  13. GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
  14. Pl.hideFlags = HideFlags.NotEditable;
  15.  
  16. //对于GameObject的某个组件单独使用HideFlags.NotEditable,
  17. //只会使得当前组件不可编辑,但GameObject的其他组件扔可编辑。
  18. t.hideFlags = HideFlags.NotEditable;
  19. Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
  20. tf.hideFlags = HideFlags.NotEditable;
  21. }
  22. }

NotEditable

5 Mathf类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Approximately_ts : MonoBehaviour {
  5. void Start () {
  6. float[] f={0.0f,2.0f,3.0f};
  7. ==/) ? true : false;
  8. bool b2 = Mathf.Approximately(1.0f, 10.0f/10.0f);
  9. Debug.Log("b1:"+b1);
  10. Debug.Log("b2:" + b2);
  11. Mathf.Min(f);
  12. }
  13. }

Approximately

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Clamp_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Debug.Log(, , ));
  9. Debug.Log(, , ));
  10. Debug.Log(, , ));
  11. //方法Clamp01的返回值范围为[0,1]
  12. Debug.Log("当value<0时:" + Mathf.Clamp01(-0.1f));
  13. Debug.Log("当0<value<1时:" + Mathf.Clamp01(0.5f));
  14. Debug.Log("当value>1时:" + Mathf.Clamp01(1.1f));
  15. }
  16. }

Clamp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ClosestPowerOfTwo_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Debug.Log());
  9. Debug.Log());
  10. Debug.Log());
  11. }
  12. }

ClosestPowerOfTwo

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class DegAndRad_ts : MonoBehaviour {
  5. void Start () {
  6. //从角度到弧度转换常量
  7. Debug.Log("Mathf.Deg2Rad:" + Mathf.Deg2Rad);
  8. //从弧度到角度转换常量
  9. Debug.Log("Mathf.Rad2Deg:" + Mathf.Rad2Deg);
  10. }
  11. }

DegAndRad

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class DeltaAngle_ts : MonoBehaviour {
  5. void Start () {
  6. //1180=360*3+100,即求100和90之间的夹角
  7. Debug.Log(Mathf.DeltaAngle(, ));
  8. //-1130=-360*3-50,即求-50和90之间的夹角
  9. Debug.Log(Mathf.DeltaAngle(-, ));
  10. //-1200=-360*3-120,即求-120和90之间的夹角
  11. Debug.Log(Mathf.DeltaAngle(-, ));
  12. }
  13. }

DeltaAngle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Infinity_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Debug.Log("0:" + Mathf.Infinity);
  9. Debug.Log("1:" + Mathf.Infinity / 10000.0f);
  10. Debug.Log("2:" + Mathf.Infinity / Mathf.Infinity);
  11. }
  12. }

Infinity

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class InverseLerp_ts : MonoBehaviour {
  5. void Start () {
  6. float f,from,to,v;
  7. from=-10.0f;
  8. to=30.0f;
  9. v=10.0f;
  10. f = Mathf.InverseLerp(from,to,v);
  11. Debug.Log("当0<f'<1时:"+f);
  12. v = -20.0f;
  13. f = Mathf.InverseLerp(from, to, v);
  14. Debug.Log("当f'<0时:" + f);
  15. v = 40.0f;
  16. f = Mathf.InverseLerp(from, to, v);
  17. Debug.Log("当f'>1时:" + f);
  18. }
  19. }

InverseLerp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Lerp_ts : MonoBehaviour {
  5. float r, g, b;
  6. void FixedUpdate () {
  7. r = Mathf.Lerp(0.0f,1.0f,Time.time*0.2f);
  8. g = Mathf.Lerp(0.0f, 1.0f, -1.0f+Time.time * 0.2f);
  9. b = Mathf.Lerp(0.0f, 1.0f, -2.0f+Time.time * 0.2f);
  10. light.color = new Color(r, g, b);
  11. }
  12. }

Lerp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LerpAngle_ts : MonoBehaviour {
  5. void Start () {
  6. float a, b;
  7. a = -50.0f;
  8. b = 400.0f;
  9. //a'=360-50=310,b'=-360+400=40,从而可知c=90,
  10. //从a'沿着逆时针方向可经90度到b',故返回值f=a+c*t=-50+90*0.3=-23
  11. Debug.Log("test1:"+Mathf.LerpAngle(a,b,0.3f));
  12.  
  13. a = 400.0f;
  14. b = -50.0f;
  15. //a'=-360+400=40,b'=360-50=310,从而可知c=90,
  16. //从a'沿着顺时针方向可经90度到b',故返回值f=a-c*t=400-90*0.3=373
  17. Debug.Log("test2:" + Mathf.LerpAngle(a, b, 0.3f));
  18. }
  19. }

LerpAngle

  1. using UnityEngine;
  2. using System.Collections;
  3. public class MoveTowards_ts : MonoBehaviour
  4. {
  5. void Start()
  6. {
  7. float a, b, d;
  8. a = 10.0f;
  9. b = -10.0f;
  10. d = 5.0f;
  11. //a>b,且a-d>b,返回值为a-d
  12. Debug.Log("Test01:" + Mathf.MoveTowards(a, b, d));
  13. d = 50.0f;
  14. //a>b,且a-d<b,返回值为b
  15. Debug.Log("Test02:" + Mathf.MoveTowards(a, b, d));
  16.  
  17. a = 10.0f;
  18. b = 50.0f;
  19. d = 5.0f;
  20. //a<b,且a+d<b,返回值为a+d
  21. Debug.Log("Test03:" + Mathf.MoveTowards(a, b, d));
  22. d = 50.0f;
  23. //a<b,且a+d>b,返回值为b
  24. Debug.Log("Test04:" + Mathf.MoveTowards(a, b, d));
  25. }
  26. }

MoveTowards

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MoveTowardsAngle_ts : MonoBehaviour
  5. {
  6. float targets = 0.0f;
  7. float speed = 40.0f;
  8. void Update()
  9. {
  10. //每帧不超过speed * Time.deltaTime度
  11. float angle = Mathf.MoveTowardsAngle(transform.eulerAngles.y, targets, speed * Time.deltaTime);
  12. transform.eulerAngles = , angle, );
  13. }
  14. void OnGUI()
  15. {
  16. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "顺时针旋转90度"))
  17. {
  18. targets += 90.0f;
  19. }
  20. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "逆时针旋转90度"))
  21. {
  22. targets -= 90.0f;
  23. }
  24. }
  25. }

MoveTowardsAngle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class PingPong_ts : MonoBehaviour {
  5. void Start () {
  6. float f, t, l;
  7. t = 11.0f;
  8. l = 5.0f;
  9. f = Mathf.PingPong(t,l);
  10. Debug.Log("l>0,|t|%2l<=l时:"+f);
  11. t = 17.0f;
  12. l = 5.0f;
  13. f = Mathf.PingPong(t, l);
  14. Debug.Log("l>0,|t|%2l>l时:" + f);
  15. t = 11.0f;
  16. l = -5.0f;
  17. f = Mathf.PingPong(t, l);
  18. Debug.Log("l<0,|t|%2l<=l时:" + f);
  19. t = 17.0f;
  20. l = -5.0f;
  21. f = Mathf.PingPong(t, l);
  22. Debug.Log("l<0,|t|%2l>l时:" + f);
  23. }
  24. }

PingPong

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Repeat_ts : MonoBehaviour {
  5. void Start () {
  6. float f, t, l;
  7. t = 12.5f;
  8. l = 5.3f;
  9. f = Mathf.Repeat(t,l);
  10. Debug.Log("t>0,l>0时:"+f);
  11. t = -12.5f;
  12. l = -5.3f;
  13. f = Mathf.Repeat(t, l);
  14. Debug.Log("t<0,l<0时:" + f);
  15. t = 12.5f;
  16. l = -5.3f;
  17. f = Mathf.Repeat(t, l);
  18. Debug.Log("t>0,l<0时:" + f);
  19. t = -12.5f;
  20. l = 5.3f;
  21. f = Mathf.Repeat(t, l);
  22. Debug.Log("t<0,l>0时:" + f);
  23. t = -12.5f;
  24. l = 0.0f;
  25. f = Mathf.Repeat(t, l);
  26. Debug.Log("t<0,l==0时:" + f);
  27. }
  28. }

Repeat

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Round_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //设Round(f)中f=a.b
  9. Debug.Log("b<0.5,f>0:" + Mathf.Round(2.49f));
  10. Debug.Log("b<0.5,f<0:" + Mathf.Round(-2.49f));
  11. Debug.Log("b>0.5,f>0:" + Mathf.Round(2.61f));
  12. Debug.Log("b>0.5,f<0:" + Mathf.Round(-2.61f));
  13. Debug.Log("b=0.5,a为偶数,f>0:" + Mathf.Round(6.5f));
  14. Debug.Log("b=0.5,a为偶数,f<0:" + Mathf.Round(-6.5f));
  15. Debug.Log("b=0.5,a为奇数,f>0:" + Mathf.Round(7.5f));
  16. Debug.Log("b=0.5,a为奇数,f<0:" + Mathf.Round(-7.5f));
  17. }
  18. }

Round

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SmoothDamp_ts : MonoBehaviour
  5. {
  6. float targets = 110.0f;//目标值
  7. float cv1 = 0.0f, cv2 = 0.0f;
  8. float maxSpeeds = 50.0f;//每帧最大值
  9. float f1 = 10.0f, f2 = 10.0f;//起始值
  10. void FixedUpdate()
  11. {
  12. //maxSpeed取默认值
  13. f1 = Mathf.SmoothDamp(f1, targets, ref cv1, 0.5f);
  14. Debug.Log("f1:" + f1);
  15. Debug.Log("cv1:" + cv1);
  16. //maxSpeed取有限值50.0f
  17. f2 = Mathf.SmoothDamp(f2, targets, ref cv2, 0.5f, maxSpeeds);
  18. Debug.Log("f2:" + f2);
  19. Debug.Log("cv2:" + cv2);
  20. }
  21. }

SmoothDamp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SmoothDampAngle_ts : MonoBehaviour
  5. {
  6. public Transform targets;
  7. float smoothTime = 0.3f;
  8. float distance = 5.0f;
  9. float yVelocity = 0.0f;
  10. void Update()
  11. {
  12. //返回平滑阻尼角度值
  13. float yAngle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targets.eulerAngles.y, ref yVelocity, smoothTime);
  14. Vector3 positions = targets.position;
  15. //由于使用transform.LookAt,此处计算targets的-z轴方向距离targets为distance,
  16. //欧拉角为摄像机绕target的y轴旋转yAngle的坐标位置
  17. positions += Quaternion.Euler(, yAngle, ) * , , -distance);
  18. //向上偏移2个单位
  19. transform.position = positions + new Vector3(0.0f, 2.0f, 0.0f);
  20. transform.LookAt(targets);
  21. }
  22. void OnGUI()
  23. {
  24. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "将targets旋转60度"))
  25. {
  26. //更改targets的eulerAngles
  27. targets.eulerAngles += new Vector3(0.0f, 60.0f, 0.0f);
  28. }
  29. }
  30. }

SmoothDampAngle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SmoothStep_ts : MonoBehaviour {
  5. float min = 10.0f;
  6. float max = 110.0f;
  7. float f1, f2=0.0f;
  8.  
  9. void FixedUpdate () {
  10. //f1为SmoothStep插值返回值
  11. f1 = Mathf.SmoothStep(min,max,Time.time);
  12. //计算相邻两帧插值的变化
  13. f2 = f1 - f2;
  14. Debug.Log("f1:"+f1);
  15. Debug.Log("f2:" + f2);
  16. f2 = f1;
  17. }
  18. }

SmoothStep

6 Matrix4x4类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MultiplyVector_ts : MonoBehaviour
  5. {
  6. public Transform tr;
  7. Matrix4x4 mv0 = Matrix4x4.identity;
  8. Matrix4x4 mv1 = Matrix4x4.identity;
  9.  
  10. void Start()
  11. {
  12. //分别设置变换矩阵mv0和mv1的位置变换和角度变换都不为0
  13. mv0.SetTRS(Vector3.one * 10.0f, Quaternion.Euler(new Vector3(0.0f, 30.0f, 0.0f)), Vector3.one);
  14. mv1.SetTRS(Vector3.one * 10.0f, Quaternion.Euler(new Vector3(0.0f, 0.6f, 0.0f)), Vector3.one);
  15. }
  16.  
  17. void Update()
  18. {
  19. //用tr来定位变换后的向量
  20. tr.position = mv1.MultiplyVector(tr.position);
  21. }
  22. void OnGUI()
  23. {
  24. if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "方向旋转30度"))
  25. {
  26. Vector3 v = mv0.MultiplyVector(new Vector3(10.0f, 0.0f, 0.0f));
  27. //打印旋转后的向量,其方向发生了旋转
  28. Debug.Log("变换后向量:"+v);
  29. //打印旋转后向量的长度,
  30. //尽管mv0的位置变换不为0,但变换后向量的长度应与变换前相同
  31. Debug.Log("变换后向量模长:" + v.magnitude);
  32. }
  33. }
  34. }

MultiplyVector

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class OrthoAndPerspective_ts : MonoBehaviour
  5. {
  6. Matrix4x4 Perspective = Matrix4x4.identity;//透视投影变量
  7. Matrix4x4 ortho = Matrix4x4.identity;//正交投影变量
  8. //声明变量,用于记录正交视口的左、右、下、上的值
  9. float l, r, b, t;
  10. void Start()
  11. {
  12. //设置透视投影矩阵
  13. Perspective = Matrix4x4.Perspective(65.0f, 1.5f, 0.1f, 500.0f);
  14. t = 10.0f;
  15. b = -t;
  16. //为防止视图变形需要与 Camera.main.aspect相乘
  17. l = b * Camera.main.aspect;
  18. r = t * Camera.main.aspect;
  19. //设置正交投影矩阵
  20. ortho = Matrix4x4.Ortho(l, r, b, t, 0.1f, 100.0f);
  21. }
  22.  
  23. void OnGUI()
  24. {
  25. //使用默认正交投影
  26. if (GUI.Button(new Rect(10.0f, 8.0f, 150.0f, 20.0f), "Reset Ortho"))
  27. {
  28. Camera.main.orthographic = true;
  29. Camera.main.ResetProjectionMatrix();
  30. Camera.main.orthographicSize = 5.1f;
  31. }
  32. //使用自定义正交投影
  33. if (GUI.Button(new Rect(10.0f, 38.0f, 150.0f, 20.0f), "use Ortho"))
  34. {
  35. ortho = Matrix4x4.Ortho(l, r, b, t, 0.1f, 100.0f);
  36. Camera.main.orthographic = true;
  37. Camera.main.ResetProjectionMatrix();
  38. Camera.main.projectionMatrix = ortho;
  39. Camera.main.orthographicSize = 5.1f;
  40. }
  41. //使用自定义透视投影
  42. if (GUI.Button(new Rect(10.0f, 68.0f, 150.0f, 20.0f), "use Perspective"))
  43. {
  44. Camera.main.orthographic = false;
  45. Camera.main.projectionMatrix = Perspective;
  46. }
  47. //恢复系统默认透视投影
  48. if (GUI.Button(new Rect(10.0f, 98.0f, 150.0f, 20.0f), "Reset Perspective"))
  49. {
  50. Camera.main.orthographic = false;
  51. Camera.main.ResetProjectionMatrix();
  52. }
  53. }
  54. }

OrthoAndPerspective

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SetTRS_ts : MonoBehaviour
  5. {
  6. Vector3 v1 = Vector3.one;
  7. Vector3 v2 = Vector3.zero;
  8.  
  9. void Start()
  10. {
  11. Matrix4x4 m1 = Matrix4x4.identity;
  12. //Position沿Y轴增加5个单位,绕Y轴旋转45度,放缩2倍
  13. m1.SetTRS(Vector3.up * , Quaternion.Euler(Vector3.up * 45.0f), Vector3.one * 2.0f);
  14. //也可以使用如下静态方法设置m1变换
  15. //m1 = Matrix4x4.TRS(Vector3.up * 5, Quaternion.Euler(Vector3.up * 45.0f), Vector3.one * 2.0f);
  16. v2 = m1.MultiplyPoint3x4(v1);
  17. Debug.Log("v1的值:" + v1);
  18. Debug.Log("v2的值:" + v2);
  19. }
  20.  
  21. void FixedUpdate()
  22. {
  23. Debug.DrawLine(Vector3.zero, v1, Color.green);
  24. Debug.DrawLine(Vector3.zero, v2, Color.red);
  25. }
  26. }

SetTRS

7 Object类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Destroy_ts : MonoBehaviour {
  5. public GameObject GO,Cube;
  6. void Start () {
  7. //5秒后销毁GO对象的Rigidbody组件
  8. Destroy(GO.rigidbody,5.0f);
  9. //7秒后销毁GO对象中的Destroy_ts脚本
  10. Destroy(GO.GetComponent<Destroy_ts>(),7.0f);
  11. //10秒后销毁Cube对象,同时Cube对象的所有组件及子类将一并销毁
  12. Destroy(Cube, 10.0f);
  13. }
  14. }

Destroy

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class DontDestoryOnLoad_ts : MonoBehaviour
  5. {
  6. public GameObject g1, g2;
  7. public Renderer re1, re2;
  8. void Start()
  9. {
  10. //g1指向一个顶层父物体对象,在导入新Scene时g1被保存
  11. DontDestroyOnLoad(g1);
  12. //g2指向一个子类对象,在导入新Scene时会发现g2没有被保存
  13. DontDestroyOnLoad(g2);
  14. //re1指向一个顶层父物体的Renderer组件,在导入新Scene时re1被保存
  15. DontDestroyOnLoad(re1);
  16. //re2指向一个子类对象的renderer组件,在导入新Scene时会发现re2指向的对象及组件没有被保存
  17. DontDestroyOnLoad(re2);
  18. Application.LoadLevel("FindObjectsOfType_unity");
  19. }
  20. }

DontDestoryOnLoad

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class FindObjectOfType_ts : MonoBehaviour {
  5. void Start () {
  6. GameObject[] gos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
  7. foreach(GameObject go in gos){
  8. //1.5秒后销毁除摄像机外的所有GameObject
  9. if (go.name != "Main Camera")
  10. {
  11. Destroy(go, 1.5f);
  12. }
  13. }
  14.  
  15. Rigidbody[] rbs = FindObjectsOfType(typeof(Rigidbody))as Rigidbody[];
  16. foreach(Rigidbody rb in rbs){
  17. //启用除球体外的所有刚体的重力感应
  18. if(rb.name!="Sphere"){
  19. rb.useGravity = true;
  20. }
  21. }
  22. }
  23. }

FindObjectOfType

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GetInstanceID_ts : MonoBehaviour {
  5. void Start () {
  6. Debug.Log("gameObject的ID:"+gameObject.GetInstanceID());
  7. Debug.Log("transform的ID:"+transform.GetInstanceID());
  8.  
  9. GameObject g1, g2;
  10. //从GameObject创建一个对象
  11. g1=GameObject.CreatePrimitive(PrimitiveType.Cube);
  12. //克隆对象
  13. g2=Instantiate(g1,Vector3.zero,Quaternion.identity)as GameObject;
  14.  
  15. Debug.Log("GameObject g1的ID:"+g1.GetInstanceID());
  16. Debug.Log("Transform g1的ID:"+g1.transform.GetInstanceID());
  17.  
  18. Debug.Log("GameObject g2的ID:" + g2.GetInstanceID());
  19. Debug.Log("Transform g2的ID:" + g2.transform.GetInstanceID());
  20. }
  21. }

GetInstanceID

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Instantiate_ts : MonoBehaviour {
  5. public GameObject A;
  6. public Transform B;
  7. public Rigidbody C;
  8. void Start () {
  9. Object g1 = Instantiate(A,Vector3.zero,Quaternion.identity) as Object;
  10. Debug.Log("克隆一个Object对象g1:"+g1);
  11. GameObject g2 = Instantiate(A, Vector3.zero, Quaternion.identity) as GameObject;
  12. Debug.Log("克隆一个GameObject对象g2:" + g2);
  13. Transform t1 = Instantiate(B, Vector3.zero, Quaternion.identity) as Transform;
  14. Debug.Log("克隆一个Transform对象t1:" + t1);
  15. Rigidbody r1 = Instantiate(C, Vector3.zero, Quaternion.identity) as Rigidbody;
  16. Debug.Log("克隆一个Rigidbody对象r1:" + r1);
  17. }
  18. }

Instantiate

8 Quaternion类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Angle_ts : MonoBehaviour {
  5. void Start()
  6. {
  7. Quaternion q1 = Quaternion.identity;
  8. Quaternion q2 = Quaternion.identity;
  9. q1.eulerAngles = new Vector3(10.0f, 20.0f, 30.0f);
  10. float f1 = Quaternion.Angle(q1,q2);
  11. float f2 = 0.0f;
  12. Vector3 v1 = Vector3.zero;
  13. q1.ToAngleAxis(out f2, out v1);
  14.  
  15. Debug.Log("f1:" + f1);
  16. Debug.Log("f2:" + f2);
  17. Debug.Log("q1的欧拉角:" + q1.eulerAngles + " q1的rotation:" + q1);
  18. Debug.Log("q2的欧拉角:" + q2.eulerAngles + " q2的rotation:" + q2);
  19. }
  20. }

Angle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Dot_ts : MonoBehaviour {
  5. public Transform A, B;
  6. Quaternion q1=Quaternion.identity;
  7. Quaternion q2=Quaternion.identity;
  8. float f;
  9.  
  10. void Start () {
  11. A.eulerAngles = new Vector3(0.0f,40.0f,0.0f);
  12. //B比A绕Y轴多转360度
  13. B.eulerAngles = new Vector3(0.0f, 360.0f+40.0f, 0.0f);
  14. q1 = A.rotation;
  15. q2 = B.rotation;
  16. f = Quaternion.Dot(q1,q2);
  17. Debug.Log("q1的rotation:"+q1);
  18. Debug.Log("q2的rotation:" + q2);
  19. Debug.Log("q1的欧拉角:" + q1.eulerAngles);
  20. Debug.Log("q2的欧拉角:" + q2.eulerAngles);
  21. Debug.Log("Dot(q1,q2):"+f);
  22. }
  23. }

Dot

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Euler_ts : MonoBehaviour
  5. {
  6. //记录欧拉角,单位为角度,可以在Inspector面板中设置
  7. public float ex, ey, ez;
  8. //用于记录计算结果
  9. float qx, qy, qz, qw;
  10. float PIover180 = 0.0174532925f;//常量
  11. Quaternion Q = Quaternion.identity;
  12. void OnGUI()
  13. {
  14. if (GUI.Button(new Rect(10.0f, 10.0f, 100.0f, 45.0f), "计算"))
  15. {
  16. Debug.Log("欧拉角:" + " ex:" + ex + " ey:" + ey + " ez:" + ez);
  17. //调用方法计算
  18. Q = Quaternion.Euler(ex, ey, ez);
  19. Debug.Log("Q.x:" + Q.x + " Q.y:" + Q.y + " Q.z:" + Q.z + " Q.w:" + Q.w);
  20. //测试算法
  21. ex = ex * PIover180 / 2.0f;
  22. ey = ey * PIover180 / 2.0f;
  23. ez = ez * PIover180 / 2.0f;
  24. qx = Mathf.Sin(ex) * Mathf.Cos(ey) * Mathf.Cos(ez) + Mathf.Cos(ex) * Mathf.Sin(ey) * Mathf.Sin(ez);
  25. qy = Mathf.Cos(ex) * Mathf.Sin(ey) * Mathf.Cos(ez) - Mathf.Sin(ex) * Mathf.Cos(ey) * Mathf.Sin(ez);
  26. qz = Mathf.Cos(ex) * Mathf.Cos(ey) * Mathf.Sin(ez) - Mathf.Sin(ex) * Mathf.Sin(ey) * Mathf.Cos(ez);
  27. qw = Mathf.Cos(ex) * Mathf.Cos(ey) * Mathf.Cos(ez) + Mathf.Sin(ex) * Mathf.Sin(ey) * Mathf.Sin(ez);
  28. Debug.Log(" qx:" + qx + " qy:" + qy + " qz:" + qz + " qw:" + qw);
  29. }
  30. }
  31. }

Euler

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EulerAngle_ts : MonoBehaviour
  5. {
  6. public Transform A, B;
  7. Quaternion rotations=Quaternion.identity;
  8. Vector3 eulerAngle = Vector3.zero;
  9. float speed = 10.0f;
  10.  
  11. void Update()
  12. {
  13. //第一种方式:将Quaternion赋值给transform的rotation
  14. rotations.eulerAngles = new Vector3(0.0f, speed * Time.time, 0.0f);
  15. A.rotation = rotations;
  16. //第二种方式:将三维向量代表的欧拉角直接赋值给transform的eulerAngles
  17. eulerAngle = new Vector3(0.0f, speed * Time.time, 0.0f);
  18. B.eulerAngles = eulerAngle;
  19. }
  20. }

EulerAngle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class FromToRotation_ts : MonoBehaviour
  5. {
  6. public Transform A, B, C, D;
  7. Quaternion q1 = Quaternion.identity;
  8.  
  9. void Update()
  10. {
  11. //使用实例方法
  12. //不可直接使用C.rotation.SetFromToRotation(A.position,B.position);
  13. q1.SetFromToRotation(A.position, B.position);
  14. C.rotation = q1;
  15. //使用类方法
  16. D.rotation = Quaternion.FromToRotation(A.position, B.position);
  17. //在Scene视图中绘制直线
  18. Debug.DrawLine(Vector3.zero, A.position, Color.white);
  19. Debug.DrawLine(Vector3.zero, B.position, Color.white);
  20. Debug.DrawLine(C.position, C.position + new Vector3(0.0f, 1.0f, 0.0f), Color.white);
  21. Debug.DrawLine(C.position, C.TransformPoint(Vector3.up * 1.5f), Color.white);
  22. Debug.DrawLine(D.position, D.position + new Vector3(0.0f, 1.0f, 0.0f), Color.white);
  23. Debug.DrawLine(D.position, D.TransformPoint(Vector3.up * 1.5f), Color.white);
  24. }
  25. }

FromToRotation

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Inverse_ts : MonoBehaviour
  5. {
  6. public Transform A, B;
  7. void Start()
  8. {
  9. Quaternion q1 = Quaternion.identity;
  10. Quaternion q2 = Quaternion.identity;
  11. q1.eulerAngles = new Vector3(10.0f, 20.0f, 30.0f);
  12. q2 = Quaternion.Inverse(q1);
  13.  
  14. A.rotation = q1;
  15. B.rotation = q2;
  16.  
  17. Debug.Log("q1的欧拉角:" + q1.eulerAngles + " q1的rotation:" + q1);
  18. Debug.Log("q2的欧拉角:" + q2.eulerAngles + " q2的rotation:" + q2);
  19. }
  20. }

Inverse

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LookRotation_ts : MonoBehaviour
  5. {
  6. public Transform A, B, C, D;
  7. Quaternion q1 = Quaternion.identity;
  8.  
  9. void Update()
  10. {
  11. //使用实例方法
  12. //不可直接使用C.rotation.SetLookRotation(A.position,B.position);
  13. q1.SetLookRotation(A.position, B.position);
  14. C.rotation = q1;
  15. //使用类方法
  16. D.rotation = Quaternion.LookRotation(A.position, B.position);
  17. //绘制直线,请在Scene视图中查看
  18. Debug.DrawLine(Vector3.zero, A.position, Color.white);
  19. Debug.DrawLine(Vector3.zero, B.position, Color.white);
  20. Debug.DrawLine(C.position, C.TransformPoint(Vector3.up * 2.5f), Color.white);
  21. Debug.DrawLine(C.position, C.TransformPoint(Vector3.forward * 2.5f), Color.white);
  22. Debug.DrawLine(D.position, D.TransformPoint(Vector3.up * 2.5f), Color.white);
  23. Debug.DrawLine(D.position, D.TransformPoint(Vector3.forward * 2.5f), Color.white);
  24. }
  25. }

LookRotation

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class QxQ_ts : MonoBehaviour {
  5. public Transform A, B;
  6.  
  7. void Start () {
  8. //设置A的欧拉角
  9. //试着更改各个分量查看B的不同旋转状态
  10. A.eulerAngles = new Vector3(1.0f,1.5f,2.0f);
  11. }
  12.  
  13. void Update () {
  14. B.rotation *= A.rotation;
  15. //输出B的欧拉角,注意观察B的欧拉角变化
  16. Debug.Log(B.eulerAngles);
  17. }
  18. }

QxQ

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class QxV_ts : MonoBehaviour
  5. {
  6. public Transform A;
  7. float speed = 0.1f;
  8. //初始化A的position和eulerAngles
  9. void Start()
  10. {
  11. A.position = Vector3.zero;
  12. A.eulerAngles = new Vector3(0.0f, 45.0f, 0.0f);
  13. }
  14.  
  15. void Update()
  16. {
  17. //沿着A的自身坐标系的forward方向每帧前进speed距离
  18. A.position += A.rotation * (Vector3.forward * speed);
  19. Debug.Log(A.position);
  20. }
  21. }

QxV

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RotateTowards_ts : MonoBehaviour {
  5. public Transform A, B, C;
  6. float speed = 10.0f;
  7.  
  8. void Update()
  9. {
  10. C.rotation = Quaternion.RotateTowards(A.rotation, B.rotation, Time.time * speed-40.0f);
  11. Debug.Log("C与A的欧拉角的差值:" + (C.eulerAngles-A.eulerAngles) + " maxDegreesDelta:" + (Time.time * speed - 40.0f));
  12. }
  13. }

RotateTowards

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SetFromToRotation_ts : MonoBehaviour {
  5. public Transform A, B, C;
  6. Quaternion q1 = Quaternion.identity;
  7.  
  8. void Update () {
  9. //不可直接使用C.rotation.SetFromToRotation(A.position,B.position);
  10. q1.SetFromToRotation(A.position,B.position);
  11. C.rotation = q1;
  12.  
  13. Debug.DrawLine(Vector3.zero,A.position,Color.red);
  14. Debug.DrawLine(Vector3.zero, B.position, Color.green);
  15. Debug.DrawLine(C.position, C.position+new Vector3(0.0f,1.0f,0.0f), Color.black);
  16. Debug.DrawLine(C.position, C.TransformPoint(Vector3.up*1.5f), Color.yellow);
  17. }
  18. }

SetFromToRotation

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SetLookRotation_ts : MonoBehaviour
  5. {
  6. public Transform A, B, C;
  7. Quaternion q1 = Quaternion.identity;
  8.  
  9. void Update()
  10. {
  11. //不可直接使用C.rotation.SetLookRotation(A.position,B.position);
  12. q1.SetLookRotation(A.position, B.position);
  13. C.rotation = q1;
  14. //分别绘制A、B和C.right的朝向线
  15. //请在Scene视图中查看
  16. Debug.DrawLine(Vector3.zero, A.position, Color.red);
  17. Debug.DrawLine(Vector3.zero, B.position, Color.green);
  18. Debug.DrawLine(C.position, C.TransformPoint(Vector3.right * 2.5f), Color.yellow);
  19. Debug.DrawLine(C.position, C.TransformPoint(Vector3.forward * 2.5f), Color.black);
  20. //分别打印C.right与A、B的夹角
  21. Debug.Log("C.right与A的夹角:" + Vector3.Angle(C.right, A.position));
  22. Debug.Log("C.right与B的夹角:" + Vector3.Angle(C.right, B.position));
  23. //C.up与B的夹角
  24. Debug.Log("C.up与B的夹角:" + Vector3.Angle(C.up, B.position));
  25. }
  26. }

SetLookRotation

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Slerp_ts : MonoBehaviour
  5. {
  6. public Transform A, B, C, D;
  7. float speed = 0.2f;
  8. //分别演示方法Slerp和Lerp的使用
  9. void Update()
  10. {
  11. C.rotation = Quaternion.Slerp(A.rotation, B.rotation, Time.time * speed);
  12. D.rotation = Quaternion.Lerp(A.rotation, B.rotation, Time.time * speed);
  13. }
  14. }

Slerp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ToAngleAxis_ts : MonoBehaviour
  5. {
  6. public Transform A, B;
  7. float angle;
  8. Vector3 axis = Vector3.zero;
  9.  
  10. void Update()
  11. {
  12. //使用ToAngleAxis获取A的Rotation的旋转轴和角度
  13. A.rotation.ToAngleAxis(out angle, out axis);
  14. //使用AngleAxis设置B的rotation,使得B的rotation状态的和A相同
  15. //可以在程序运行时修改A的rotation查看B的状态
  16. B.rotation = Quaternion.AngleAxis(angle, axis);
  17. }
  18. }

ToAngleAxis

9 Random类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class insideUnitCircle_ts : MonoBehaviour
  5. {
  6. public GameObject go;
  7.  
  8. void Start()
  9. {
  10. //每隔0.4秒执行一次use_rotationUniform方法
  11. InvokeRepeating("use_rotationUniform", 1.0f, 0.4f);
  12. }
  13.  
  14. void use_rotationUniform()
  15. {
  16. //在半径为5的圆内随机位置实例化一个GameObject对象
  17. //Vector2实例转为Vector3时,z轴分量默认为0
  18. Instantiate(go, Random.insideUnitCircle * 5.0f, Quaternion.identity);
  19. //在半径为5的球内随机位置实例化一个GameObject对象
  20. Instantiate(go, Vector3.forward * 15.0f + 5.0f * Random.insideUnitSphere, Quaternion.identity);
  21. //在半径为5的球表面随机位置实例化一个GameObject对象
  22. Instantiate(go, Vector3.forward * 30.0f + 5.0f * Random.onUnitSphere, Quaternion.identity);
  23. }
  24. }

insideUnitCircle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class rotationUniform_ts : MonoBehaviour
  5. {
  6. public GameObject go;
  7. GameObject cb, sp;
  8. GameObject cb1, sp1;
  9.  
  10. void Start()
  11. {
  12. //分别获取cb、sp、cb1和sp1对象
  13. cb = GameObject.Find("Cube");
  14. sp = GameObject.Find("Cube/Sphere");
  15. cb1 = GameObject.Find("Cube1");
  16. sp1 = GameObject.Find("Cube1/Sphere1");
  17. //每隔0.4秒执行一次use_rotationUniform方法
  18. InvokeRepeating("use_rotationUniform", 1.0f, 0.4f);
  19. }
  20.  
  21. void use_rotationUniform()
  22. {
  23. //使用rotationUniform产生符合均匀分布特征的rotation
  24. cb.transform.rotation = Random.rotationUniform;
  25. //使用rotation产生一个随机rotation
  26. cb1.transform.rotation = Random.rotation;
  27. //分别在sp和sp1的位置实例化一个GameObject对象
  28. Instantiate(go, sp.transform.position, Quaternion.identity);
  29. Instantiate(go, sp1.transform.position, Quaternion.identity);
  30. }
  31. }

rotationUniform

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Seed_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //设置随机数的种子
  9. //不同的种子产生不同的随机数序列
  10. //对于相同的种子,在程序每次启动时其序列是相同的
  11. Random.seed = ;
  12. }
  13. void Update()
  14. {
  15. Debug.Log(Random.value);
  16. }
  17. }

Seed

10 Rigidbody类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class AddExplosionForce_ts : MonoBehaviour
  5. {
  6. public Rigidbody A;
  7. public Transform Z;//Scene视图中显示爆炸点坐标
  8. Vector3 E = Vector3.zero;//爆炸点坐标
  9. float F, R, y_m;
  10. bool is_change = false;
  11.  
  12. void Start()
  13. {
  14. //初始位置使得爆炸点和A的X、Y轴坐标值相等
  15. //可以更改F及R的大小查看运行时效果
  16. E = A.position - new Vector3(0.0f, 0.0f, 3.0f);
  17. F = 40.0f;
  18. R = 10.0f;
  19. y_m = 0.0f;
  20. A.transform.localScale = Vector3.one * 2.0f;
  21. Z.position = E;
  22. }
  23.  
  24. void FixedUpdate()
  25. {
  26. if (is_change)
  27. {
  28. A.AddExplosionForce(F, E, R, y_m);
  29. is_change = false;
  30. }
  31. }
  32.  
  33. void OnGUI()
  34. {
  35. //当爆炸点和A的重心的两个坐标轴的值相等时,A将平移不旋转
  36. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "刚体移动不旋转"))
  37. {
  38. is_change = true;
  39. inits();
  40. }
  41. //虽然受力大小不变,但产生扭矩发生旋转
  42. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "刚体发生移动但受力大小不变"))
  43. {
  44. inits();
  45. A.position += new Vector3(0.5f, -0.5f, 0.0f);
  46. is_change = true;
  47. }
  48. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "按最近表面距离计算力的大小"))
  49. {
  50. inits();
  51. A.position += new Vector3(0.0f, 2.0f, 0.0f);
  52. is_change = true;
  53. }
  54. //Y轴的偏移改变了A的原始方向
  55. //可以更改y_m的值查看不同的效果
  56. if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "Y轴发生偏移"))
  57. {
  58. inits();
  59. is_change = true;
  60. A.position += new Vector3(0.0f, 2.0f, 0.0f);
  61. y_m = -2.0f;
  62. }
  63. }
  64. //初始化数据
  65. void inits()
  66. {
  67. A.velocity = Vector3.zero;
  68. A.angularVelocity = Vector3.zero;
  69. A.position = E + new Vector3(0.0f, 0.0f, 3.0f);
  70. A.transform.rotation = Quaternion.identity;
  71. y_m = 0.0f;
  72. }
  73. }

AddExplosionForce

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class AddForceAtPosition_ts : MonoBehaviour
  5. {
  6. public Rigidbody A, B, C;
  7. Vector3 m_force = new Vector3(0.0f, 0.0f, 10.0f);
  8.  
  9. void FixedUpdate()
  10. {
  11. //当力的作用点在刚体重心时,刚体不发生旋转
  12. A.AddForceAtPosition(m_force, A.transform.position, ForceMode.Force);
  13. //当力的作用点不在刚体重心时,由于作用点的扭矩使得刚体发生旋转
  14. B.AddForceAtPosition(m_force, B.transform.position + new Vector3(0.0f, 0.3f, 0.0f), ForceMode.Force);
  15. //但是,当力的作用点与刚体重心坐标的差值向量与作用力的方向同向时不发生旋转
  16. C.AddForceAtPosition(m_force, C.transform.position + new Vector3(0.0f, 0.0f, 0.3f), ForceMode.Force);
  17. Debug.Log("A的欧拉角:" + A.transform.eulerAngles);
  18. Debug.Log("B的欧拉角:" + B.transform.eulerAngles);
  19. Debug.Log("C的欧拉角:" + C.transform.eulerAngles);
  20. }
  21. }

AddForceAtPosition

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class AddTorque_ts : MonoBehaviour {
  5. public Rigidbody R;
  6. Vector3 m_torque = new Vector3(0.0f,10.0f,0.0f);
  7. void Start () {
  8. R.transform.localScale = new Vector3(2.0f,2.0f,2.0f);
  9. R.mass = 1.0f;
  10. R.angularDrag = 0.0f;
  11. Debug.Log("刚体默认的最大角速度:"+R.maxAngularVelocity);
  12. //可以使用如下代码更改刚体的最大角速度
  13. //R.maxAngularVelocity = 10.0f;
  14. }
  15.  
  16. void FixedUpdate () {
  17. //每帧给物体添加一个扭矩,使其转速不断加快
  18. R.AddTorque(m_torque,ForceMode.Force);
  19. Debug.Log("刚体当前角速度:"+R.angularVelocity);
  20. }
  21. }

AddTorque

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ATorC_ts : MonoBehaviour
  5. {
  6. //开始接触
  7. void OnTriggerEnter(Collider other)
  8. {
  9. Debug.Log("A物体的OnTriggerEnter被调用,被接触的物体为" + other.name);
  10. }
  11. //结束接触
  12. void OnTriggerExit(Collider other)
  13. {
  14. Debug.Log("A物体的OnTriggerExit被调用,被接触的物体为" + other.name);
  15. }
  16. //保持接触
  17. void OnTriggerStay(Collider other)
  18. {
  19. Debug.Log("A物体的OnTriggerStay被调用,被接触的物体为" + other.name);
  20. }
  21. //开始碰撞
  22. void OnCollisionEnter(Collision collision)
  23. {
  24. Debug.Log("A物体的OnCollisionEnter被调用,被碰撞的物体为" + collision.gameObject.name);
  25. }
  26. //退出碰撞
  27. void OnCollisionExit(Collision collision)
  28. {
  29. Debug.Log("A物体的OnCollisionExit被调用,被碰撞的物体为" + collision.gameObject.name);
  30. }
  31. //保持碰撞
  32. void OnCollisionStay(Collision collision)
  33. {
  34. Debug.Log("A物体的OnCollisionStay被调用,被碰撞的物体为" + collision.gameObject.name);
  35. }
  36. }

ATorC

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class BTorC_ts : MonoBehaviour
  5. {
  6. void OnTriggerEnter(Collider other)
  7. {
  8. Debug.Log("B物体的OnTriggerEnter被调用,被接触的物体为" + other.name);
  9. }
  10. void OnTriggerExit(Collider other)
  11. {
  12. Debug.Log("B物体的OnTriggerExit被调用,被接触的物体为" + other.name);
  13. }
  14. void OnTriggerStay(Collider other)
  15. {
  16. Debug.Log("B物体的OnTriggerStay被调用,被接触的物体为" + other.name);
  17. }
  18.  
  19. void OnCollisionEnter(Collision collision)
  20. {
  21. Debug.Log("B物体的OnCollisionEnter被调用,被碰撞的物体为" + collision.gameObject.name);
  22. }
  23.  
  24. void OnCollisionExit(Collision collision)
  25. {
  26. Debug.Log("B物体的OnCollisionExit被调用,被碰撞的物体为" + collision.gameObject.name);
  27. }
  28.  
  29. void OnCollisionStay(Collision collision)
  30. {
  31. Debug.Log("B物体的OnCollisionStay被调用,被碰撞的物体为" + collision.gameObject.name);
  32. }
  33. }

BTorC

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ClosestPointOnBounds_ts : MonoBehaviour
  5. {
  6. public Rigidbody r;
  7. void Start()
  8. {
  9. r.position = new Vector3(0.0f,4.0f,0.0f);
  10. Debug.Log(r.ClosestPointOnBounds(new Vector3(5.0f, 4.0f, 0.0f)));
  11. }
  12. }

ClosestPointOnBounds

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CollisionDetectionMode_ts : MonoBehaviour
  5. {
  6. public Rigidbody A, B;
  7. Vector3 v1, v2;
  8. void Start()
  9. {
  10. A.useGravity = false;
  11. B.useGravity = false;
  12. v1 = A.position;
  13. v2 = B.position;
  14. }
  15. void OnGUI()
  16. {
  17. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Discrete模式不被穿越"))
  18. {
  19. inists();
  20. A.collisionDetectionMode = CollisionDetectionMode.Discrete;
  21. B.collisionDetectionMode = CollisionDetectionMode.Discrete;
  22. A.velocity = new Vector3(0.0f,-10.0f,0.0f);
  23. }
  24. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Discrete模式被穿越"))
  25. {
  26. inists();
  27. A.collisionDetectionMode = CollisionDetectionMode.Discrete;
  28. B.collisionDetectionMode = CollisionDetectionMode.Discrete;
  29. A.velocity = new Vector3(0.0f, -40.0f, 0.0f);
  30. }
  31. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "Continuous模式不被穿越"))
  32. {
  33. inists();
  34. A.collisionDetectionMode = CollisionDetectionMode.Continuous;
  35. B.collisionDetectionMode = CollisionDetectionMode.Continuous;
  36. A.velocity = new Vector3(0.0f, -20.0f, 0.0f);
  37. }
  38. if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "Continuous模式被穿越"))
  39. {
  40. inists();
  41. A.collisionDetectionMode = CollisionDetectionMode.Continuous;
  42. B.collisionDetectionMode = CollisionDetectionMode.Continuous;
  43. A.velocity = new Vector3(0.0f, -15.0f, 0.0f);
  44. B.velocity = new Vector3(0.0f, 15.0f, 0.0f);
  45. }
  46. if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "ContinuousDynamic模式"))
  47. {
  48. inists();
  49. A.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
  50. B.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
  51. A.velocity = new Vector3(0.0f, -200.0f, 0.0f);
  52. B.velocity = new Vector3(0.0f, 200.0f, 0.0f);
  53. }
  54. if (GUI.Button(new Rect(10.0f, 260.0f, 200.0f, 45.0f), "重置"))
  55. {
  56. inists();
  57. }
  58. }
  59. //初始化A、B
  60. void inists() {
  61. A.position = v1;
  62. A.rotation = Quaternion.identity;
  63. A.velocity = Vector3.zero;
  64. A.angularVelocity = Vector3.zero;
  65. B.position = v2;
  66. B.rotation = Quaternion.identity;
  67. B.velocity = Vector3.zero;
  68. B.angularVelocity = Vector3.zero;
  69. }
  70. }

CollisionDetectionMode

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Drag_ts : MonoBehaviour
  5. {
  6. public Rigidbody R;
  7. float drags = 20.0f;
  8. ";
  9. //初始化R.drag
  10. void Start()
  11. {
  12. R.drag = drags;
  13. }
  14.  
  15. void OnGUI()
  16. {
  17. GUI.Label(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Gravity:" + Physics.gravity);
  18. str = (GUI.TextField(new Rect(10.0f, 60.0f, 200.0f, 45.0f), str));
  19. if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "compute"))
  20. {
  21. drags = float.Parse(str);
  22. R.drag = drags;
  23. }
  24. GUI.Label(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "Velocity:" + R.velocity.y);
  25. GUI.Label(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "drag:" + drags);
  26. }
  27. }

Drag

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ForceMode_ts : MonoBehaviour
  5. {
  6. public Rigidbody A, B, C, D;
  7. //作用力向量
  8. Vector3 forces = new Vector3(10.0f, 0.0f, 0.0f);
  9.  
  10. void Start()
  11. {
  12. //初始化四个刚体的质量,使其相同
  13. A.mass = 2.0f;
  14. B.mass = 2.0f;
  15. C.mass = 2.0f;
  16. D.mass = 2.0f;
  17. //对A、B、C、D采用不同的作用力方式
  18. //注意此处只是对物体增加了1帧的作用力
  19. //如果要对刚体产生持续作用力请把以下代码放在FixedUpdate()方法中
  20. A.AddForce(forces, ForceMode.Force);
  21. B.AddForce(forces, ForceMode.Acceleration);
  22. C.AddForce(forces, ForceMode.Impulse);
  23. D.AddForce(forces, ForceMode.VelocityChange);
  24. }
  25.  
  26. void FixedUpdate()
  27. {
  28. Debug.Log("ForceMode.Force作用方式下A每帧增加的速度:" + A.velocity);
  29. Debug.Log("ForceMode.Acceleration作用方式下B每帧增加的速度:" + B.velocity);
  30. Debug.Log("ForceMode.Impulse作用方式下C每帧增加的速度:" + C.velocity);
  31. Debug.Log("ForceMode.VelocityChange作用方式下D每帧增加的速度:" + D.velocity);
  32. }
  33. }

ForceMode

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GetRelativePointVelocity_ts : MonoBehaviour
  5. {
  6. public Rigidbody A;
  7. string str = "";
  8. void Start()
  9. {
  10. //给A施加一帧的力,使其产生速度
  11. A.AddForce(Vector3.forward * 100.0f);
  12. }
  13. void FixedUpdate()
  14. {
  15. //A.transform.TransformPoint(Vector3.forward):获取A的局部坐标系中Vector3.forward点在世界坐标系中的坐标值
  16. //这样A.GetPointVelocity(A.transform.TransformPoint(Vector3.forward))和
  17. //A.GetRelativePointVelocity(Vector3.forward)返回的是同一点的速度,即它们的返回值应该相等。
  18. Debug.Log(str + "GetPointVelocity: " + A.GetPointVelocity(A.transform.TransformPoint(Vector3.forward)));
  19. Debug.Log(str + "GetRelativePointVelocity: " + A.GetRelativePointVelocity(Vector3.forward));
  20. }
  21. void OnGUI()
  22. {
  23. //当刚体角速度为Vector3.zero时,任何点的速度都和刚体速度相等
  24. //当刚体角速度不为Vector3.zero时,坐标系中各个点的速度是不等的
  25. //GetPointVelocity和GetRelativePointVelocity只是两种计算坐标点的不同方法
  26. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "增加角速度"))
  27. {
  28. A.angularVelocity = new Vector3(0.0f, 45.0f, 0.0f);
  29. str = "增加角速度后,";
  30. }
  31. }
  32. }

GetRelativePointVelocity

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GraAndKin_ts : MonoBehaviour
  5. {
  6. public Rigidbody A, B;
  7. string str_AG = "";
  8. string str_AK = "";
  9. string str_BK = "";
  10. Vector3 v1, v2;
  11. void Start()
  12. {
  13. //为了更好的演示,将重力加速度降低
  14. Physics.gravity = new Vector3(0.0f,-0.5f,0.0f);
  15. A.useGravity = false;
  16. B.useGravity = false;
  17. A.isKinematic = false;
  18. B.isKinematic = false;
  19. str_AG = "A开启重力感应";
  20. str_AK = "A关闭物理感应";
  21. str_BK = "B关闭物理感应";
  22. v1 = A.position;
  23. v2 = B.position;
  24. }
  25.  
  26. void OnGUI()
  27. {
  28. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), str_AG))
  29. {
  30. if (A.useGravity)
  31. {
  32. A.useGravity = false;
  33. str_AG = "A开启重力感应";
  34. }
  35. else
  36. {
  37. A.useGravity = true;
  38. str_AG = "A关闭重力感应";
  39. }
  40. }
  41. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), str_AK))
  42. {
  43. if (A.isKinematic)
  44. {
  45. A.isKinematic = false;
  46. str_AK = "A关闭物理感应";
  47. }
  48. else
  49. {
  50. A.isKinematic = true;
  51. str_AK = "A开启物理感应";
  52. }
  53. }
  54. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), str_BK))
  55. {
  56. if (B.isKinematic)
  57. {
  58. B.isKinematic = false;
  59. str_BK = "B关闭物理感应";
  60. }
  61. else
  62. {
  63. B.isKinematic = true;
  64. str_BK = "B开启物理感应";
  65. }
  66. }
  67. if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "重置"))
  68. {
  69. A.position = v1;
  70. A.rotation = Quaternion.identity;
  71. B.position = v2;
  72. B.rotation = Quaternion.identity;
  73. }
  74. }
  75. }

GraAndKin

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class inertiaTensor_ts : MonoBehaviour
  5. {
  6. void OnGUI()
  7. {
  8. if (GUI.Button(new Rect(10.0f, 10.0f, 160.0f, 45.0f), "X轴惯性张量大于Y轴"))
  9. {
  10. transform.position = , , );
  11. //transform绕Z轴旋转45度
  12. transform.rotation = Quaternion.Euler(0.0f, 0.0f, 45.0f);
  13. //设置rigidbody的惯性张量
  14. //X轴分量值大于Y轴,则刚体会向X轴方向倾斜
  15. rigidbody.inertiaTensor = new Vector3(15.0f, 10.0f, 1.0f);
  16. }
  17. if (GUI.Button(new Rect(10.0f, 60.0f, 160.0f, 45.0f), "Y轴惯性张量大于X轴"))
  18. {
  19. transform.position = , , );
  20. transform.rotation = Quaternion.Euler(0.0f, 0.0f, 45.0f);
  21. //设置rigidbody的惯性张量
  22. //X轴分量值小于Y轴,则刚体会向Y轴方向倾斜
  23. rigidbody.inertiaTensor = new Vector3(5.0f, 10.0f, 1.0f);
  24. }
  25. if (GUI.Button(new Rect(10.0f, 110.0f, 160.0f, 45.0f), "X轴和Y轴惯性张量相同"))
  26. {
  27. transform.position = , , );
  28. transform.rotation = Quaternion.Euler(0.0f, 0.0f, 45.0f);
  29. //设置rigidbody的惯性张量
  30. //X轴和Y轴惯性张量相同,则刚体会保持静止
  31. rigidbody.inertiaTensor = new Vector3(10.0f, 10.0f, 1.0f);
  32. }
  33. }
  34. }

inertiaTensor

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Mass_ts : MonoBehaviour
  5. {
  6. public Rigidbody r1, r2, r3, r4, r5;
  7. Vector3 v3 = Vector3.zero;
  8. void Start()
  9. {
  10. //r1和r2质量不同,但它们的速度始终相同
  11. //r4和r5质量不同,当r3以同样的速度撞r4和r5后速度明显不同
  12. r1.mass = 0.1f;
  13. r2.mass = 5.0f;
  14. r3.mass = 2.0f;
  15. r4.mass = 0.1f;
  16. r5.mass = 4.0f;
  17.  
  18. r3.useGravity = false;
  19. r4.useGravity = false;
  20. r5.useGravity = false;
  21. v3 = r3.position;
  22. }
  23.  
  24. void FixedUpdate()
  25. {
  26. Debug.Log(Time.time + " R1的速度:" + r1.velocity);
  27. Debug.Log(Time.time + " R2的速度:" + r2.velocity);
  28. Debug.Log(Time.time + " R3的速度:" + r3.velocity);
  29. Debug.Log(Time.time + " R4的速度:" + r4.velocity);
  30. Debug.Log(Time.time + " R5的速度:" + r5.velocity);
  31. }
  32.  
  33. void OnGUI()
  34. {
  35. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "用R3撞R4"))
  36. {
  37. r3.position = v3;
  38. r3.rotation = Quaternion.identity;
  39. r3.velocity = new Vector3(4.0f, 0.0f, 0.0f);
  40. }
  41.  
  42. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "用R3撞R5"))
  43. {
  44. r3.position = v3;
  45. r3.rotation = Quaternion.identity;
  46. r3.velocity = new Vector3(0.0f, 0.0f, 4.0f);
  47. }
  48. }
  49. }

Mass

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Mds_ts : MonoBehaviour
  5. {
  6. public Rigidbody A, B;
  7. public static bool is_AC = false, is_BC = false;
  8. public static Vector3 A_v = Vector3.zero, B_v = Vector3.zero;
  9.  
  10. void Start()
  11. {
  12. //如果不使用SetDensity则scale的大小对刚体质量无影响
  13. Debug.Log("A的质量mass:" + A.mass);
  14. A.transform.localScale = A.transform.localScale * 2.0f;
  15. Debug.Log("scale值放大后A的质量mass:" + A.mass);
  16. A.transform.localScale = A.transform.localScale / 2.0f;
  17.  
  18. //注意,如果要使用SetDensity请先设定scale值再设置Density
  19. //否则一旦density确定质量也就确定了,再去设置scale将对质量改变不起作用
  20. A.transform.localScale = A.transform.localScale * 2.0f;
  21. A.SetDensity(2.0f);
  22. Debug.Log("改变density和scale值后A的质量mass:" + A.mass);
  23. //给A一个初始速度
  24. A.velocity = new Vector3(0.0f, 0.0f, 10.0f);
  25.  
  26. Debug.Log("碰撞前mA*vA+mB*vB=" + (A.mass * (A.velocity.x + A.velocity.y + A.velocity.z) + B.mass * (B.velocity.x + B.velocity.y + B.velocity.z)));
  27. }
  28.  
  29. void FixedUpdate()
  30. {
  31. if (is_AC && is_BC)
  32. {
  33. Debug.Log("碰撞后mA*vA+mB*vB=" + (A.mass * (A.velocity.x + A.velocity.y + A.velocity.z) + B.mass * (B.velocity.x + B.velocity.y + B.velocity.z)));
  34. }
  35. }
  36. }

Mds

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MdsA_ts : MonoBehaviour {
  5.  
  6. void OnCollisionExit(Collision collisionInfo)
  7. {
  8. Mds_ts.A_v = rigidbody.velocity;
  9. Mds_ts.is_AC = true;
  10. }
  11. }

MdsA

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MdsB_ts : MonoBehaviour {
  5. void OnCollisionExit(Collision collisionInfo)
  6. {
  7. Mds_ts.B_v = rigidbody.velocity;
  8. Mds_ts.is_BC = true;
  9. }
  10. }

MdsB

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MovePOrR_ts : MonoBehaviour
  5. {
  6. public Rigidbody A;
  7. bool is_pr = false;
  8. void Start()
  9. {
  10. A.velocity = Vector3.forward * 20.0f;
  11. A.angularVelocity = Vector3.up * 90.0f;
  12. //当isKinematic == true时刚体的动力学模拟将失效
  13. //此时可以使用MovePosition和MoveRotation对刚体进行移动和旋转
  14. A.isKinematic = true;
  15. }
  16. void FixedUpdate()
  17. {
  18. if (is_pr)
  19. {
  20. A.MovePosition(A.position + Vector3.forward * Time.deltaTime);
  21. Quaternion deltaRotation = Quaternion.Euler(Vector3.up * 90.0f * Time.deltaTime);
  22. A.MoveRotation(A.rotation * deltaRotation);
  23. }
  24. }
  25. void OnGUI()
  26. {
  27. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "刚体移动与旋转"))
  28. {
  29. is_pr = true;
  30. }
  31. }
  32. }

MovePOrR

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SleepOrWake_ts : MonoBehaviour
  5. {
  6. public Rigidbody A;
  7. void Awake()
  8. {
  9. A.Sleep();
  10. }
  11. void OnGUI()
  12. {
  13. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Sleep"))
  14. {
  15. if (!A.IsSleeping())
  16. {
  17. A.Sleep();
  18. }
  19. }
  20. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "WakeUp"))
  21. {
  22. if (A.IsSleeping())
  23. {
  24. A.WakeUp();
  25. }
  26. }
  27. Debug.Log("A物体的Y坐标:" + A.transform.position.y+" A物体是否处于休眠状态:"+A.IsSleeping());
  28. }
  29. }

SleepOrWake

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SweepTest_ts : MonoBehaviour
  5. {
  6. public GameObject A, B;
  7. RaycastHit hit;
  8. float len = 10.0f;//有效探测距离
  9. void Start()
  10. {
  11. A.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
  12. B.transform.position = new Vector3(4.0f, 1.0f, 1.0f);
  13. }
  14.  
  15. void FixedUpdate()
  16. {
  17. //探测刚体A的right方向(即右侧)len距离内是否存在物体
  18. if (A.rigidbody.SweepTest(A.transform.right, out hit, len))
  19. {
  20. Debug.Log("A物体右侧存在物体:" + hit.transform.name + " 其距离A的距离为:" + hit.distance);
  21. }
  22. else
  23. {
  24. Debug.Log("A物体右侧" + len + "米范围内没检测到带碰撞器的物体!");
  25. }
  26. }
  27.  
  28. void OnGUI()
  29. {
  30. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "设置B坐标使A无法探测到"))
  31. {
  32. //重置B的position,使得物体A、B的间距大于len值
  33. B.transform.position = new Vector3(12.0f, 1.0f, 1.0f);
  34. }
  35. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "取消B中的Rigidbody组件"))
  36. {
  37. //销毁B物体中的Rigidbody组件
  38. //运行程序可以发现,B物体中是否存在Rigidbody对探测结果没有影响
  39. if (B.GetComponent<Rigidbody>())
  40. {
  41. Destroy(B.GetComponent<Rigidbody>());
  42. }
  43. }
  44. if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "取消B中的Collider组件"))
  45. {
  46. //销毁B物体中的Collider组件
  47. //运行程序可以发现,如果B中无Collider组件则A无论如何也探测不到B的存在
  48. if (B.GetComponent<Collider>())
  49. {
  50. Destroy(B.GetComponent<Collider>());
  51. }
  52. }
  53. //对B物体的状态重置
  54. if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "重置"))
  55. {
  56. B.transform.position = new Vector3(4.0f, 1.0f, 1.0f);
  57. if (!B.GetComponent<Collider>())
  58. {
  59. B.AddComponent<BoxCollider>();
  60. }
  61. if (!B.GetComponent<Rigidbody>())
  62. {
  63. B.AddComponent<Rigidbody>();
  64. B.rigidbody.useGravity = false;
  65. }
  66. }
  67. }
  68. }

SweepTest

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SweepTestAll_ts : MonoBehaviour
  5. {
  6. public GameObject A, B, C, D;
  7. RaycastHit[] hits;
  8. float len = 10.0f;//有效探测距离
  9. void Start()
  10. {
  11. A.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
  12. B.transform.position = new Vector3(4.0f, 1.0f, 1.0f);
  13. C.transform.position = new Vector3(7.0f, 1.0f, 1.0f);
  14. //D物体超出了A的有效探测距离,不会被探测到
  15. D.transform.position = new Vector3(12.0f, 1.0f, 1.0f);
  16. hits = A.rigidbody.SweepTestAll(A.transform.right, len);
  17. float l = hits.Length;
  18. Debug.Log("A探测到的物体个数为:" + l + " 它们分别是:");
  19. //遍历探测结果
  20. foreach (RaycastHit hit in hits)
  21. {
  22. Debug.Log(hit.transform.name);
  23. }
  24. }
  25. }

SweepTestAll

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class TriggerOrCollision_ts : MonoBehaviour
  5. {
  6. public GameObject A, B;
  7. Vector3 p_a, p_b;
  8. ;
  9. //将物体A、B的初始位置赋给p_a和p_b,用于重置物体组件时使用
  10. void Start()
  11. {
  12. p_a = A.transform.position;
  13. p_b = B.transform.position;
  14. }
  15. //控制物体A的移动
  16. void FixedUpdate()
  17. {
  18. )
  19. {
  20. A.transform.Translate(Vector3.forward * Time.deltaTime);
  21. }
  22. }
  23. void OnGUI()
  24. {
  25. //当A物体无Rigidbody组件时,
  26. //无论B是否有Rigidbody都不会激活A和B物体的脚本中的OnCollisionXXX或OnTriggerXXX方法
  27. if (GUI.Button(new Rect(10.0f, 10.0f, 280.0f, 45.0f), "A物体无Rigidbody组件"))
  28. {
  29. inists();
  30. which_change = ;
  31. if (A.GetComponent<Rigidbody>())
  32. {
  33. Destroy(A.GetComponent<Rigidbody>());
  34. }
  35. }
  36. //当A物体有Rigidbody组件时,
  37. //一定会激活A和B物体的脚本中的OnCollisionXXX或OnTriggerXXX方法
  38. if (GUI.Button(new Rect(10.0f, 60.0f, 280.0f, 45.0f), "A有Rigidbody组件,B无Rigidbody组件"))
  39. {
  40. inists();
  41. which_change = ;
  42. if (!A.GetComponent<Rigidbody>())
  43. {
  44. A.AddComponent<Rigidbody>();
  45. A.rigidbody.useGravity = false;
  46. }
  47. if (B.GetComponent<Rigidbody>())
  48. {
  49. Destroy(B.GetComponent<Rigidbody>());
  50. }
  51. A.rigidbody.velocity = Vector3.forward;
  52. }
  53. //当A物体有Rigidbody组件时,
  54. //且A与B物体IsTrigger都未选中时,只会激活A和B物体的脚本中的OnCollisionXXX方法
  55. if (GUI.Button(new Rect(10.0f, 110.0f, 280.0f, 45.0f), "A与B物体IsTrigger都未选中"))
  56. {
  57. inists();
  58. which_change = ;
  59. A.GetComponent<Collider>().isTrigger = false;
  60. B.GetComponent<Collider>().isTrigger = false;
  61. if (!A.GetComponent<Rigidbody>())
  62. {
  63. A.AddComponent<Rigidbody>();
  64. A.rigidbody.useGravity = false;
  65. }
  66. A.rigidbody.velocity = Vector3.forward;
  67. }
  68. //当A物体有Rigidbody组件时,
  69. //且A与B物体IsTrigger至少有一个被选中时,只会激活A和B物体的脚本中的OnTriggerXXX方法
  70. if (GUI.Button(new Rect(10.0f, 160.0f, 280.0f, 45.0f), "A物体IsTrigger被选中"))
  71. {
  72. inists();
  73. which_change = ;
  74. A.GetComponent<Collider>().isTrigger = true;
  75. if (!A.GetComponent<Rigidbody>())
  76. {
  77. A.AddComponent<Rigidbody>();
  78. A.rigidbody.useGravity = false;
  79. }
  80. A.rigidbody.velocity = Vector3.forward;
  81. }
  82. if (GUI.Button(new Rect(10.0f, 210.0f, 280.0f, 45.0f), "重置"))
  83. {
  84. inists();
  85. which_change = ;
  86. }
  87. }
  88. //初始化数据
  89. void inists()
  90. {
  91. if (A.GetComponent<Rigidbody>())
  92. {
  93. A.rigidbody.velocity = Vector3.zero;
  94. A.rigidbody.angularVelocity = Vector3.zero;
  95. }
  96. if (B.GetComponent<Rigidbody>())
  97. {
  98. B.rigidbody.velocity = Vector3.zero;
  99. B.rigidbody.angularVelocity = Vector3.zero;
  100. }
  101. A.transform.position = p_a;
  102. A.transform.rotation = Quaternion.identity;
  103. B.transform.position = p_b;
  104. B.transform.rotation = Quaternion.identity;
  105. }
  106. }

TriggerOrCollision

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Velocity_ts : MonoBehaviour {
  5. public Rigidbody r1,r2;
  6. // Use this for initialization
  7. void Start () {
  8. //给父物体r1一个向-z轴的速度,给子物体一个+z轴的速度
  9. r1.velocity = new Vector3(0.0f,0.0f,-15.0f);
  10. r2.velocity = new Vector3(0.0f, 0.0f, 10.0f);
  11. }
  12.  
  13. void OnGUI() {
  14. GUI.Label(new Rect(10.0f,8.0f,300.0f,40.0f),"R1当前速度:"+r1.velocity);
  15. GUI.Label(new Rect(10.0f,58.0f,300.0f,40.0f),"R2当前速度:"+r2.velocity);
  16. Debug.Log("R1当前速度:" + r1.velocity);
  17. Debug.Log("R2当前速度:" + r2.velocity);
  18. }
  19. }

Velocity

11 Time类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class newScene01_ts : MonoBehaviour
  5. {
  6. float t1 = 0.0f;
  7. void Update()
  8. {
  9. t1 = Time.deltaTime;
  10. }
  11. void OnGUI()
  12. {
  13. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "返回原来场景"))
  14. {
  15. Application.LoadLevel("Time_unity");
  16. }
  17. GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前游戏场景名字:" + Application.loadedLevelName);
  18. GUI.Label(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "当前游戏已运行时间Time.time:" + Time.time);
  19. GUI.Label(new Rect(10.0f, 160.0f, 400.0f, 45.0f), "当前场景已运行时间Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);
  20. GUI.Label(new Rect(10.0f, 210.0f, 300.0f, 45.0f), "上一帧消耗的时间Time.deltaTime:" + t1);
  21. GUI.Label(new Rect(10.0f, 260.0f, 300.0f, 45.0f), "固定增量时间Time.fixedTime:" + Time.fixedTime);
  22. GUI.Label(new Rect(10.0f, 310.0f, 400.0f, 45.0f), "上一帧消耗的固定增量时间Time.fixedDeltaTime:" + Time.fixedDeltaTime);
  23. GUI.Label(new Rect(10.0f, 360.0f, 300.0f, 45.0f), "游戏已运行帧数Time.frameCount:" + Time.frameCount);
  24. }
  25. }

newScene01

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RealtimeSinceStartup_ts : MonoBehaviour
  5. {
  6. public Rigidbody rg;
  7. void Start()
  8. {
  9. Debug.Log("Time.timeScale的默认时间:" + Time.timeScale);
  10. //观察刚体在timeScale变化前后的移动速度
  11. rg.velocity = Vector3.forward * 2.0f;
  12. Time.timeScale = 0.5f;
  13. }
  14. void Update()
  15. {
  16. Debug.Log("Time.timeScale的d当前值:" + Time.timeScale);
  17. Debug.Log("Time.time:" + Time.time);
  18. Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);
  19. }
  20. void OnGUI()
  21. {
  22. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Time.timeScale=0.5f"))
  23. {
  24. Time.timeScale = 0.5f;
  25. }
  26. if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Time.timeScale=1.0f"))
  27. {
  28. Time.timeScale = 1.0f;
  29. }
  30. }
  31. }

RealtimeSinceStartup

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SmoothDeltaTime_ts : MonoBehaviour
  5. {
  6. , b = ;
  7. bool c = false;
  8. void Update()
  9. {
  10. float t1, t2;
  11. t1 = Time.deltaTime;
  12. t2 = Time.smoothDeltaTime;
  13. Debug.Log("Time.deltaTime:" + t1);
  14. Debug.Log("smoothDeltaTime:" + t2);
  15. a += t1;
  16. b += t2;
  17. Debug.Log("Time.deltaTime的累加和:" + a + " smoothDeltaTime的累加和:" + b);
  18. }
  19. }

SmoothDeltaTime

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Time_ts : MonoBehaviour
  5. {
  6. float t1 = 0.0f;
  7. void Update()
  8. {
  9. t1 = Time.deltaTime;
  10. }
  11. void OnGUI()
  12. {
  13. if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "加载新场景"))
  14. {
  15. Application.LoadLevel("newScene01_unity");
  16. }
  17. GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前游戏场景名字:" + Application.loadedLevelName);
  18. GUI.Label(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "当前游戏已运行时间Time.time:" + Time.time);
  19. GUI.Label(new Rect(10.0f, 160.0f, 400.0f, 45.0f), "当前场景已运行时间Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);
  20. GUI.Label(new Rect(10.0f, 210.0f, 300.0f, 45.0f), "上一帧消耗的时间Time.deltaTime:" + t1);
  21. GUI.Label(new Rect(10.0f, 260.0f, 300.0f, 45.0f), "固定增量时间Time.fixedTime:" + Time.fixedTime);
  22. GUI.Label(new Rect(10.0f, 310.0f, 400.0f, 45.0f), "上一帧消耗的固定增量时间Time.fixedDeltaTime:" + Time.fixedDeltaTime);
  23. GUI.Label(new Rect(10.0f, 360.0f, 300.0f, 45.0f), "游戏已运行帧数Time.frameCount:" + Time.frameCount);
  24. }
  25. }

Time_ts

12 Transform类

  1. using UnityEngine;
  2. using System.Collections;
  3. public class DetachChildren_ts : MonoBehaviour
  4. {
  5. void Start () {
  6. transform.DetachChildren();
  7. }
  8. }

DetachChildren

  1. using UnityEngine;
  2. using System.Collections;
  3. //将所有子物体放大2*2*2=8倍,不包括自身。
  4. public class Foreach_ts : MonoBehaviour {
  5. void Start () {
  6. foreach (Transform child in transform)
  7. {
  8. child.localScale *= 2.0f;
  9. }
  10. }
  11. }

Foreach

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Forward_ts : MonoBehaviour {
  5. void Start () {
  6. //先给transform一个任意的欧拉角,使得transform的局部坐标系和世界坐标系方向不一致
  7. transform.eulerAngles = new Vector3(15.0f,30.0f,60.0f);
  8. //right
  9. Debug.Log("right:"+transform.right);
  10. Debug.Log("Dir:" + transform.TransformDirection(new Vector3(1.0f, 0.0f, 0.0f)));
  11. //up
  12. Debug.Log("up:" + transform.up);
  13. Debug.Log("Dir:" + transform.TransformDirection(new Vector3(0.0f, 1.0f, 0.0f)));
  14. //forward
  15. Debug.Log("forward:" + transform.forward);
  16. Debug.Log("Dir:" + transform.TransformDirection(new Vector3(0.0f, 0.0f, 1.0f)));
  17. }
  18. }

Forward

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class GetChild_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //transform的子物体数量
  9. int ct = transform.childCount;
  10. Debug.Log("子物体数量:" + ct);
  11. ; i < ct; i++)
  12. {
  13. Debug.Log("索引为" + i + "的子物体名字:" + transform.GetChild(i).name);
  14. }
  15. }
  16. }

GetChild

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class HasChanged_ts : MonoBehaviour
  5. {
  6. bool is_rotate = false;//物体旋转控制
  7. // Update is called once per frame
  8. void Update()
  9. {
  10. //当transform.hasChanged为true时打印相关信息
  11. if (transform.hasChanged)
  12. {
  13. Debug.Log("The transform has changed!");
  14. transform.hasChanged = false;
  15. }
  16. if (is_rotate)
  17. {
  18. transform.Rotate(Vector3.up * 15.0f * Time.deltaTime);
  19. }
  20. }
  21. void OnGUI()
  22. {
  23. //使物体开始旋转,物体rotation被修改
  24. if (GUI.Button(new Rect(10.0f, 10.0f, 80.0f, 45.0f), "Rotate start"))
  25. {
  26. is_rotate = true;
  27. }
  28. //停止旋转
  29. if (GUI.Button(new Rect(10.0f, 65.0f, 80.0f, 45.0f), "Rotate stop"))
  30. {
  31. is_rotate = false;
  32. }
  33. //将transform的当前位置赋给transform.position,也即transform的位置没有改变,
  34. //但是transform是position属性已经被修改,故transform.hasChanged返回值为true
  35. if (GUI.Button(new Rect(10.0f, 125.0f, 80.0f, 45.0f), "use position"))
  36. {
  37. is_rotate = false;
  38. transform.position = transform.position;
  39. }
  40. }
  41. }

HasChanged

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class InverseTransformDirection_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //转换前向量
  9. Vector3 world_v = new Vector3(10.0f, 20.0f, 30.0f);
  10. //transform绕y轴旋转90度,使transform坐标系与世界坐标系方向不一致
  11. transform.eulerAngles = new Vector3(0.0f, 90.0f, 0.0f);
  12. Vector3 local_v = transform.InverseTransformDirection(world_v);
  13. //打印transform的position,方法InverseTransformDirection与transform的position无关
  14. Debug.Log("transform position:" + transform.position);
  15. //打印transform的lossyScale,方法InverseTransformDirection与transform的lossyScale无关
  16. Debug.Log("transform lossyScale:" + transform.lossyScale);
  17. Debug.Log("world_v:" + world_v);
  18. Debug.Log("local_v:" + local_v);
  19. }
  20. }

InverseTransformDirection

  1. using UnityEngine;
  2. using System.Collections;
  3. public class InverseTransformPoint_ts : MonoBehaviour {
  4. Vector3 A = new Vector3(50.0f, 30.0f, 10.0f);
  5. Vector3 B = Vector3.zero;
  6. void Start()
  7. {
  8. B = transform.InverseTransformPoint(A);
  9. Debug.Log("transform.position:" + transform.position);
  10. Debug.Log("transform.lossyScale:" + transform.lossyScale);
  11. Debug.Log("A:" + A);
  12. Debug.Log("B:" + B);
  13. }
  14. }

InverseTransformPoint

  1. using UnityEngine;
  2. using System.Collections;
  3. public class IsChildOf_ts : MonoBehaviour
  4. {
  5. public Transform t1, t2, t3;
  6. void Start()
  7. {
  8. Debug.Log("t1是否为其自身的子类:" + t1.IsChildOf(t1));
  9. Debug.Log("t2是否为t1的子类:" + t2.IsChildOf(t1));
  10. Debug.Log("t3是否为t1的子类:" + t3.IsChildOf(t1));
  11. }
  12. }

IsChildOf

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LocalPosition_ts : MonoBehaviour {
  5. public Transform cube0, cube1;
  6. void Start () {
  7. Debug.Log("cube0 local position:" + cube0.localPosition);
  8. Debug.Log("cube0 local scale:" + cube0.localScale);
  9. Debug.Log("cube1 local position:"+cube1.localPosition);
  10. Debug.Log("cube1 local scale:" + cube1.localScale);
  11. Debug.Log("cube2 local position:" + transform.localPosition);
  12. Debug.Log("cube2 world position:" + transform.position);
  13. }
  14. }

LocalPosition

  1. using UnityEngine;
  2. using System.Collections;
  3. public class LocalScaleOrLossyScale_ts : MonoBehaviour
  4. {
  5. void Start()
  6. {
  7. Debug.Log("父物体A放缩值:" + transform.parent.localScale);
  8. Debug.Log("子物体B的全局有损放缩值:" + transform.lossyScale);
  9. Debug.Log("子物体B的局部放缩值:" + transform.localScale);
  10. //检验本注解部分的算法描述是否正确
  11. if (transform.localScale.x == (transform.lossyScale.x / transform.parent.localScale.x) &&
  12. transform.localScale.y == (transform.lossyScale.y / transform.parent.localScale.y) &&
  13. transform.localScale.z == (transform.lossyScale.z / transform.parent.localScale.z))
  14. {
  15. Debug.Log("True");
  16. }
  17. else
  18. {
  19. Debug.Log("False");
  20. }
  21. }
  22. }

LocalScaleOrLossyScale

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LocalToWorldMatrix_ts : MonoBehaviour {
  5. void Start()
  6. {
  7. //local_vector3为transform局部坐标系中的一个向量
  8. Vector3 local_vector3 = new Vector3(1.0f, 2.0f, 3.0f);
  9. Vector3 v1 = transform.localToWorldMatrix.MultiplyPoint3x4(local_vector3);
  10. Debug.Log("transform position:" + transform.position);
  11. Debug.Log("transform lossyScale:" + transform.lossyScale);
  12. Debug.Log("local_vector3:" + local_vector3);
  13. Debug.Log("local_vector3在世界坐标系中的向量为:" + v1);
  14. }
  15. }

LocalToWorldMatrix

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class LookAt_ts : MonoBehaviour
  5. {
  6. public Transform tr_look;
  7. void Update()
  8. {
  9. transform.LookAt(tr_look);
  10. tr_look.RotateAround(Vector3.zero, Vector3.up, 60.0f * Time.deltaTime);
  11. }
  12. }

LookAt

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Parent_ts : MonoBehaviour {
  5. void Start () {
  6. //返回transform的父物体的Transform
  7. Debug.Log("一级父物体名字:" + transform.parent);
  8. //返回transform的二级父物体的Transform
  9. Debug.Log("二级父物体名字:" + transform.parent.parent);
  10. //返回transform的三级父物体的Transform
  11. Debug.Log("三级父物体名字:" + transform.parent.parent.parent);
  12. //返回transform的最顶层(root)父物体的Transform
  13. Debug.Log("最顶层父物体名字:" + transform.root);
  14. }
  15. }

Parent

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Rotate1_ts : MonoBehaviour {
  5. void Start () {
  6. //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
  7. transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
  8. transform.Rotate(new Vector3(0.0f,45.0f,0.0f),Space.Self);
  9. Debug.Log("Space.Self:" + transform.eulerAngles);
  10.  
  11. //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
  12. transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
  13. transform.Rotate(new Vector3(0.0f, 45.0f, 0.0f), Space.World);
  14. Debug.Log("Space.World:" + transform.eulerAngles);
  15.  
  16. //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
  17. transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
  18. transform.Rotate(new Vector3(0.0f, 45.0f, 0.0f));
  19. Debug.Log("默认坐标系:"+transform.eulerAngles);
  20. }
  21. }

Rotate1

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Rotate2_ts : MonoBehaviour {
  5. void Start()
  6. {
  7. //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
  8. transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
  9. transform.Rotate(Vector3.up,45.0f, Space.Self);
  10. Debug.Log("绕自身坐标系的y轴方向旋转45度:" + transform.eulerAngles);
  11.  
  12. //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
  13. transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
  14. transform.Rotate(Vector3.up, 45.0f, Space.World);
  15. Debug.Log("绕世界坐标系的y轴方向旋转45度:" + transform.eulerAngles);
  16.  
  17. //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
  18. transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
  19. transform.Rotate(Vector3.up,45.0f);
  20. Debug.Log("绕默认坐标系的y轴方向旋转45度:" + transform.eulerAngles);
  21. }
  22. }

Rotate2

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RotateAround_ts : MonoBehaviour {
  5. public Transform point_r;
  6. void Update () {
  7. transform.RotateAround(point_r.position ,Vector3.up,30.0f*Time.deltaTime);
  8. }
  9. }

RotateAround

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class TransformDirection_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector3 local_v = new Vector3(1.0f, 2.0f, 3.0f);
  9. transform.eulerAngles = new Vector3(0.0f, 90.0f, 0.0f);
  10. //将local_v从局部坐标系转到世界坐标系中
  11. Vector3 world_v = transform.TransformDirection(local_v);
  12. //transform的position值不影响变换结果
  13. Debug.Log("transform position:" + transform.position);
  14. //transform的lossyScale值不影响变换结果
  15. Debug.Log("transform lossyScale:" + transform.lossyScale);
  16. Debug.Log("local_v:" + local_v);
  17. Debug.Log("world_v:" + world_v);
  18. }
  19. }

TransformDirection

  1. using UnityEngine;
  2. using System.Collections;
  3. public class TransformPoint_ts : MonoBehaviour {
  4. Vector3 A=new Vector3(1.0f,2.0f,3.0f);
  5. Vector3 B=Vector3.zero;
  6. void Start () {
  7. B = transform.TransformPoint(A);
  8. Debug.Log("transform.position:" + transform.position);
  9. Debug.Log("transform.lossyScale:" + transform.lossyScale);
  10. Debug.Log("A:"+A);
  11. Debug.Log("B:"+B);
  12. }
  13. }

TransformPoint

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Translate1_ts : MonoBehaviour {
  5. void Start () {
  6. //沿y轴旋转30度,使得transform自身坐标系和世界坐标系x轴方向不一致
  7. transform.eulerAngles = new Vector3(0.0f, 30.0f, 0.0f);
  8. //坐标位置归零
  9. transform.position = Vector3.zero;
  10. transform.Translate(new Vector3(10.0f, 0.0f, 0.0f), Space.Self);
  11. Debug.Log("沿自身坐标系x轴移动10个距离:" + transform.position);
  12. //坐标位置归零
  13. transform.position = Vector3.zero;
  14. transform.Translate(new Vector3(10.0f, 0.0f, 0.0f), Space.World);
  15. Debug.Log("沿世界坐标系x轴移动10个距离:" + transform.position);
  16. //坐标位置归零
  17. transform.position = Vector3.zero;
  18. transform.Translate(new Vector3(10.0f, 0.0f, 0.0f));
  19. Debug.Log("沿默认坐标系x轴移动10个距离:" + transform.position);
  20. }
  21. }

Translate1

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Translate2_ts : MonoBehaviour {
  5. public Transform relativeTo;
  6. void Start () {
  7. //将relativeTo沿y轴旋转30度,使得relativeTo自身坐标系和世界坐标系x轴方向不一致
  8. relativeTo.eulerAngles = new Vector3(0.0f, 30.0f, 0.0f);
  9. //transform坐标位置归零
  10. transform.position = Vector3.zero;
  11. transform.Translate(new Vector3(10.0f, 0.0f, 0.0f), relativeTo);
  12. Debug.Log("沿relativeTo坐标系x轴移动10个距离:" + transform.position);
  13.  
  14. //坐标位置归零
  15. transform.position = Vector3.zero;
  16. transform.Translate(new Vector3(10.0f, 0.0f, 0.0f));
  17. Debug.Log("沿默认坐标系x轴移动10个距离:" + transform.position);
  18. }
  19. }

Translate2

  1. using UnityEngine;
  2. using System.Collections;
  3. public class WorldToLocalMatrix_ts : MonoBehaviour {
  4. public Transform t1;
  5. void Start()
  6. {
  7. Vector3 v1 = transform.worldToLocalMatrix.MultiplyPoint3x4(t1.position);
  8. Debug.Log("transform position:"+transform.position);
  9. Debug.Log("transform lossyScale:" + transform.lossyScale);
  10. Debug.Log("t1 position:"+t1.position);
  11. Debug.Log("t1 相对transform的向量为:"+v1);
  12. }
  13. }

WorldToLocalMatrix

13 Vector2类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Angle_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Debug.Log("1:" + Vector2.Angle(new Vector2(1.0f, 0.0f), new Vector2(-1.0f, 0.0f)));
  9. Debug.Log("2:" + Vector2.Angle(new Vector2(1.0f, 0.0f), new Vector2(-1.0f, -1.0f)));
  10. Debug.Log("3:" + Vector2.Angle(new Vector2(0.0f, 0.0f), new Vector2(-1.0f, 0.0f)));
  11. }
  12. }

Angle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ClampMagnitude_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector2 A = new Vector2(10.0f, 20.0f);
  9. //K值大于1时返回A的初始值
  10. float b = A.magnitude * 3.0f;
  11. Vector2 C = Vector2.ClampMagnitude(A, b);
  12. Debug.Log("K值大于1时返回A的初始值:" + C.ToString());
  13. //K值小于-1时返回A的初始值
  14. b = -A.magnitude * 3.0f;
  15. C = Vector2.ClampMagnitude(A, b);
  16. Debug.Log("K值小于-1时返回A的初始值:" + C.ToString());
  17. //K值介于-1和1之间时时按算法求值
  18. b = A.magnitude * 0.7f;
  19. C = Vector2.ClampMagnitude(A, b);
  20. Debug.Log("K值介于-1和1之间时时按算法求值:" + C.ToString());
  21. //当A为零向量时返回值永远为零向量
  22. A.Set(0.0f,0.0f);
  23. b = A.magnitude * 0.7f;
  24. C = Vector2.ClampMagnitude(A, b);
  25. Debug.Log("当A为零向量时返回值永远为零向量:" + C.ToString());
  26. }
  27. }

ClampMagnitude

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EqualOrNot_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. //A、B小数点后五位相等,第六位足够接近时返回true
  9. Vector2 A = new Vector2(1.123453f, 3.123453f);
  10. Vector2 B = new Vector2(1.123459f, 3.123459f);
  11. Debug.Log("First:" + (A == B));
  12. //A、B小数点后五位相等,但第六位不够接近时也可能返回false
  13. A = new Vector2(1.123451f, 3.123451f);
  14. Debug.Log("Second:" + (A == B));
  15. //A、B小数点后六位相等时一定返回true
  16. A = new Vector2(1.1234560f, 3.1234560f);
  17. B = new Vector2(1.1234569f, 3.1234569f);
  18. Debug.Log("Third:" + (A == B));
  19. }
  20. }

EqualOrNot

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Lerp_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector2 v1 = new Vector2(4.0f, 12.0f);
  9. Vector2 v2 = new Vector2(9.0f, 20.0f);
  10. //e<0时返回值为v1的值
  11. Debug.Log("e<0时返回值为v1的值:" + Vector2.Lerp(v1, v2, -2.0f));
  12. //e>1时返回值为v2的值
  13. Debug.Log("e>1时返回值为v2的值:" + Vector2.Lerp(v1, v2, 2.0f));
  14. //e>0且e<1时按插值算法求返回值
  15. Debug.Log("e>0且e<1时按插值算法求返回值:" + Vector2.Lerp(v1, v2, 0.7f));
  16. }
  17. }

Lerp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MoveTowards_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector2 A = new Vector2(10.0f, 20.0f);
  9. Vector2 B = new Vector2(30.0f, 40.0f);
  10. //当K=1时返回B的值
  11. float sp = (B - A).magnitude;
  12. Vector2 C = Vector2.MoveTowards(A, B, sp);
  13. Debug.Log("当K=1时返回B的值:" + C.ToString());
  14. //当K>1时返回B的值
  15. sp += 10.0f;
  16. C = Vector2.MoveTowards(A, B, sp);
  17. Debug.Log("当K>1时返回B的值:" + C.ToString());
  18. //当K=0时返回A的值
  19. sp = 0.0f;
  20. C = Vector2.MoveTowards(A, B, sp);
  21. Debug.Log("当K=0时返回A的值:" + C.ToString());
  22. //当K<0时按算法计算
  23. sp = -10.0f;
  24. C = Vector2.MoveTowards(A, B, sp);
  25. Debug.Log("当K<0时按算法计算:" + C.ToString());
  26. //当K>0且K<1时按算法计算
  27. sp = (B - A).magnitude * 0.7f;
  28. C = Vector2.MoveTowards(A, B, sp);
  29. Debug.Log("当K>0且K<1时按算法计算:" + C.ToString());
  30. }
  31. }

MoveTowards

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Normalize_ts : MonoBehaviour {
  5. void Start()
  6. {
  7. Vector2 v1 = new Vector2(1.0f, 2.0f);
  8. //使用属性不改变原始值,有返回值
  9. Vector2 v2 = v1.normalized;
  10. Debug.Log("使用属性v2.normalized后v1的值:" + v1);
  11. Debug.Log("使用属性v2.normalized后的返回值v2:" + v2);
  12.  
  13. v1.Set(1.0f, 2.0f);
  14. //使用实例方法改变原始值,无返回值
  15. v1.Normalize();
  16. Debug.Log("使用实例方法v1.Normalize后v1的值:" + v1);
  17. }
  18. }

Normalize

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Scale_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector2 v2 = new Vector2(1.0f, 2.0f);
  9. //实例方法会改变原始向量v2的值,无返回值
  10. v2.Scale(new Vector2(2.0f, 3.0f));
  11. Debug.Log("使用实例方法v2.Scale后v2值:" + v2);
  12.  
  13. //使用Set方法重设v2
  14. v2.Set(1.0f, 2.0f);
  15. //类方法不会改变原始向量的值,其返回值为放缩后的向量
  16. Vector2 v3 = Vector2.Scale(v2, new Vector2(4.0f, 6.0f));
  17. Debug.Log("使用类方法Vector2.Scale后v2值:" + v2);
  18. Debug.Log("使用类方法Vector2.Scale后v3值:" + v3);
  19. }
  20. }

Scale

14 Vector3类

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Angle_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Debug.Log("1:" + Vector3.Angle(Vector3.right, -Vector3.right));
  9. Debug.Log("2:" + Vector3.Angle(Vector3.right, -(Vector3.right + Vector3.up)));
  10. Debug.Log("3:" + Vector3.Angle(Vector3.right, Vector3.zero));
  11. }
  12. }

Angle

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ClampMagnitude_ts : MonoBehaviour {
  5. void Start () {
  6. Vector3 ts = new Vector3(1.0f,2.0f,3.0f);
  7. Debug.Log("ts的单位向量为:"+ts.normalized+" ts模长为:"+ts.magnitude);
  8.  
  9. Debug.Log("当f值大于ts模长时:");
  10. float f = ts.magnitude + 1.0f;
  11. Vector3 ov = Vector3.ClampMagnitude(ts,f);
  12. Debug.Log("ov向量:" + ov.ToString()+"其单位向量为:"+ov.normalized + " ov的模长为:" + ov.magnitude);
  13.  
  14. Debug.Log("当f值小于ts模长时:");
  15. f = ts.magnitude - 1.0f;
  16. ov = Vector3.ClampMagnitude(ts,f);
  17. Debug.Log("ov向量:" + ov.ToString() + "其单位向量为:" + ov.normalized + " ov的模长为:" + ov.magnitude);
  18. }
  19. }

ClampMagnitude

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Cross_ts : MonoBehaviour {
  5. public Transform A, B;
  6. Vector3 A_v, B_v;
  7. Vector3 C_v = Vector3.zero;
  8.  
  9. void Update()
  10. {
  11. A_v = A.position;
  12. B_v = B.position;
  13. C_v = Vector3.Cross(A_v,B_v);
  14.  
  15. Debug.DrawLine(Vector3.zero, A_v , Color.green);
  16. Debug.DrawLine(Vector3.zero, B_v, Color.yellow);
  17. Debug.DrawLine(Vector3.zero, C_v, Color.red);
  18. }
  19. }

Cross

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Dot_ts : MonoBehaviour {
  5. public Transform A, B;
  6. Vector3 A_lv, AB_v;
  7. string str = "";
  8.  
  9. void Update()
  10. {
  11. //将A的自身坐标系的forward向量转向时间坐标系中
  12. A_lv = A.TransformDirection(Vector3.forward);
  13. //A到B的差向量
  14. AB_v = B.position-A.position;
  15. float f = Vector3.Dot(A_lv, AB_v);
  16. ){
  17. str = "B在A自身坐标系的前方";
  18. }
  19. )
  20. {
  21. str = "B在A自身坐标系的后方";
  22. }
  23. else {
  24. str = "B在A自身坐标系的正左方或右方";
  25. }
  26. //旋转A物体使得A的自身forward方向不断改变
  27. //虽然A、B的世界坐标都未改变,且在世界坐标系中A和B的位置关系没有改变
  28. //但在A的自身坐标系中B的相对位置在不断改变
  29. A.Rotate(new Vector3(0.0f,1.0f,0.0f));
  30. }
  31. void OnGUI(){
  32. GUI.Label(new Rect(10.0f,10.0f,200.0f,60.0f),str);
  33. }
  34. }

Dot

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EqualOrNot_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector3 v1 = new Vector3(1.123451f, 2.123451f, 3.123451f);
  9. Vector3 v2 = new Vector3(1.123452f, 2.123452f, 3.123452f);
  10. if (v1 == v2)
  11. {
  12. Debug.Log("v1==v2");
  13. }
  14. else
  15. {
  16. Debug.Log("v1!=v2");
  17. }
  18. }
  19. }

EqualOrNot

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Lerp_ts : MonoBehaviour
  5. {
  6. public Transform start_T;//起始点位置物体
  7. public Transform end_T;//结束点位置物体
  8. Vector3 start_v, end_v;//起始和结束的两个Vector3
  9. float speed = 0.2f;//控制移动速度
  10. float last_time;//控制插值系数范围
  11. void Start()
  12. {
  13. start_v = start_T.position;
  14. end_v = end_T.position;
  15. last_time = Time.time;
  16. }
  17. void Update()
  18. {
  19. //利用插值改变物体位置坐标达到运动目的
  20. transform.position = Vector3.Lerp(start_v, end_v, (Time.time - last_time) * speed);
  21. if (transform.position == end_v)
  22. {
  23. //对调起始和结束点坐标
  24. transform.position = start_v;
  25. start_v = end_v;
  26. end_v = transform.position;
  27. transform.position = start_v;
  28. last_time = Time.time;
  29. }
  30. }
  31. }

Lerp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class MoveTowards_ts : MonoBehaviour {
  5. public Transform from_T, to_T;
  6. Vector3 from_v, to_v;
  7. Vector3 moves = Vector3.zero;
  8. float speed = 0.5f;
  9.  
  10. void Start()
  11. {
  12. //初始化起始位置
  13. from_v = from_T.position;
  14. to_v = to_T.position;
  15. }
  16.  
  17. void Update()
  18. {
  19. //在向量差值to_v-from_v的模长时间内moves从from_v移动到to_v
  20. moves = Vector3.MoveTowards(from_v, to_v, Time.time * speed);
  21. //绘制从原点到slerps的红线,并保留100秒以便观察
  22. //运行时只能在scene视图中查看
  23. Debug.DrawLine(Vector3.zero, moves, Color.red, 100.0f);
  24. }
  25. }

MoveTowards

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Normalized_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector3 v1 = new Vector3(1.0f, 2.0f, 3.0f);
  9. Vector3 v2 = v1.normalized;
  10. //使用v2 = v1.normalized后v1的值不会改变,而v2的值为v1的单位向量。
  11. Debug.Log("v2 = v1.normalized后v1的值:" + v1);
  12. Debug.Log("v2 = v1.normalized后v2的值:" + v2);
  13. //"v2 = Vector3.Normalize(v1)"与"v2 = v1.normalized"实现功能相同,但不常用。
  14. v2 = Vector3.Normalize(v1);
  15. Debug.Log("v2 = Vector3.Normalize(v1)后v1的值:" + v1);
  16. Debug.Log("v2 = Vector3.Normalize(v1)后v2的值:" + v2);
  17. //v1.Normalize()等于将v1自身进行了单位化处理,v1变成了新的向量。
  18. v1.Normalize();
  19. Debug.Log("v1.Normalize()后v1的值:" + v1);
  20. }
  21. }

Normalized

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class OrthoNormalize_ts : MonoBehaviour {
  5. public Transform one_T, two_T;
  6. Vector3 one_v, two_v;
  7. Vector3 one_l, two_l;
  8.  
  9. void Start()
  10. {
  11. //初始化起始位置
  12. one_v = one_T.position;
  13. two_v = two_T.position;
  14. //记录初始化位置
  15. one_l = one_v;
  16. two_l = two_v;
  17. }
  18.  
  19. void Update()
  20. {
  21. Vector3.OrthoNormalize(ref one_v,ref two_v);
  22. //绘制原始向量和OrthoNormalize处理后的向量
  23. Debug.DrawLine(Vector3.zero, one_l, Color.black);
  24. Debug.DrawLine(Vector3.zero, two_l, Color.white);
  25. Debug.DrawLine(Vector3.zero, one_v, Color.red);
  26. Debug.DrawLine(Vector3.zero, two_v, Color.yellow);
  27. }
  28. }

OrthoNormalize

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class OrthoNormalize2_ts : MonoBehaviour {
  5. public Transform one_T, two_T, three_T;
  6. Vector3 one_v, two_v, three_v;
  7. Vector3 one_l, two_l, three_l;
  8.  
  9. void Start()
  10. {
  11. //初始化起始位置
  12. one_v = one_T.position;
  13. two_v = two_T.position;
  14. three_v = three_T.position;
  15. //保持初始值
  16. one_l = one_v;
  17. two_l = two_v;
  18. three_l = three_v;
  19. }
  20.  
  21. void Update()
  22. {
  23. Vector3.OrthoNormalize(ref one_v, ref two_v,ref three_v);
  24. //绘制原始向量和OrthoNormalize处理后的向量
  25. Debug.DrawLine(Vector3.zero, one_l, Color.black);
  26. Debug.DrawLine(Vector3.zero, two_l, Color.white);
  27. Debug.DrawLine(Vector3.zero, three_l, Color.green);
  28. Debug.DrawLine(Vector3.zero, one_v, Color.red);
  29. Debug.DrawLine(Vector3.zero, two_v, Color.yellow);
  30. Debug.DrawLine(Vector3.zero, three_v, Color.blue);
  31. }
  32. }

OrthoNormalize2

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Project_ts : MonoBehaviour {
  5. public Transform from_T, to_T;
  6. Vector3 projects = Vector3.zero;
  7.  
  8. void Update()
  9. {
  10. projects = Vector3.Project(from_T.position, to_T.position);
  11.  
  12. Debug.DrawLine(Vector3.zero, projects, Color.black);
  13. Debug.DrawLine(Vector3.zero, from_T.position, Color.red);
  14. Debug.DrawLine(Vector3.zero, to_T.position, Color.yellow);
  15. }
  16. }

Project

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Reflect_ts : MonoBehaviour
  5. {
  6. public Transform A, B;
  7. //A_v为镜面向量,B_v为入射向量
  8. Vector3 A_v, B_v;
  9. //R_v为反射向量
  10. Vector3 R_v = Vector3.zero;
  11.  
  12. void Update()
  13. {
  14. //将镜面向量进行单位化处理,否则反射向量不一定为镜面反射
  15. A_v = A.position.normalized;
  16. B_v = B.position;
  17. R_v = Vector3.Reflect(B_v, A_v);
  18.  
  19. Debug.DrawLine(-A_v * 1.5f, A_v *1.5f, Color.black);
  20. Debug.DrawLine(Vector3.zero, B_v, Color.yellow);
  21. Debug.DrawLine(Vector3.zero, R_v, Color.red);
  22. }
  23. }

Reflect

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class RotateTowards_ts : MonoBehaviour
  5. {
  6. public Transform from_T, to_T;
  7. Vector3 from_v, to_v;
  8. Vector3 rotates = Vector3.zero;
  9. float speed = 0.2f;
  10. float l;
  11.  
  12. void Start()
  13. {
  14. //初始化起始位置
  15. from_v = from_T.position;
  16. to_v = to_T.position;
  17. //l取值为0时,rotates会以from_v的模长运动到to_v方向
  18. // l = 0.0f;
  19. //l取值为(to_v - from_v).sqrMagnitude时,rotates会以to_v的模长运动到to_v方向
  20. l = (to_v - from_v).sqrMagnitude;
  21. }
  22.  
  23. void Update()
  24. {
  25. //在1/speed时间内rotates从from_v移动到to_v
  26. rotates = Vector3.RotateTowards(from_v, to_v, Time.time*speed,l);
  27. //绘制从原点到slerps的红线,并保留100秒以便观察
  28. //运行时只能在scene视图中查看
  29. Debug.DrawLine(Vector3.zero, rotates, Color.red, 100.0f);
  30. }
  31. }

RotateTowards

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Scale_ts : MonoBehaviour
  5. {
  6. void Start()
  7. {
  8. Vector3 v1 = new Vector3(1.0f, 2.0f, 3.0f);
  9. Vector3 v2 = new Vector3(4.0f, 5.0f, 6.0f);
  10. //使用v1.Scale(v2)将使向量v1按向量v2进行放缩,无返回值
  11. v1.Scale(v2);
  12. Debug.Log("使用v1.Scale(v2)后v1的值:" + v1.ToString());
  13. Debug.Log("使用v1.Scale(v2)后v2的值:" + v2.ToString());
  14. //重设v1
  15. v1.Set(1.0f, 2.0f, 3.0f);
  16. //使用v3 = Vector3.Scale(v1, v2)将会返回向量v1按向量v2进行放缩后的向量v3
  17. //v1、v2不会改变
  18. Vector3 v3 = Vector3.Scale(v1, v2);
  19. Debug.Log("使用v3=Vector3.Scale(v1,v2)后v1的值:" + v1.ToString());
  20. Debug.Log("使用v3=Vector3.Scale(v1,v2)后v2的值:" + v2.ToString());
  21. Debug.Log("使用v3=Vector3.Scale(v1,v2)后v3的值:" + v3.ToString());
  22. }
  23. }

Scale

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Slerp_ts : MonoBehaviour {
  5. public Transform from_T, to_T;
  6. Vector3 from_v, to_v;
  7. Vector3 slerps = Vector3.zero;
  8. float speed = 0.1f;
  9.  
  10. void Start () {
  11. //初始化起始位置
  12. from_v = from_T.position;
  13. to_v = to_T.position;
  14. }
  15.  
  16. void Update () {
  17. //在1/speed时间内slerps从from_v移动到to_v
  18. slerps = Vector3.Slerp(from_v,to_v,Time.time*speed);
  19. //绘制从原点到slerps的红线,并保留100秒以便观察
  20. //运行时只能在scene视图中查看
  21. Debug.DrawLine(Vector3.zero,slerps,Color.red,100.0f);
  22. }
  23. }

Slerp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SmoothDamp_ts : MonoBehaviour {
  5. public Transform from_T, to_T;
  6. public float smoothTime, maxSpeed,delta_time;
  7. Vector3 to_v;
  8. Vector3 speed = Vector3.zero;
  9.  
  10. void Start()
  11. {
  12. //初始化起始位置
  13. transform.position = from_T.position;
  14. to_v = to_T.position;
  15. //初始化系数
  16. smoothTime = 1.5f;
  17. maxSpeed = 10.0f;
  18. delta_time = 1.0f;
  19. }
  20.  
  21. void Update()
  22. {
  23. transform.position = Vector3.SmoothDamp(transform.position, to_v, ref speed, smoothTime, maxSpeed, Time.deltaTime * delta_time);
  24. }
  25. }

SmoothDamp

  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class SqrMagnitude_ts : MonoBehaviour {
  5. void Start () {
  6. Vector3 v1 = new Vector3(3.0f,4.0f,5.0f);
  7. Vector3 v2 = new Vector3(1.0f, 2.0f, 8.0f);
  8. Debug.Log("向量v1的长度:"+v1.magnitude);
  9. Debug.Log("向量v2的长度:"+v2.magnitude);
  10. float f1 = v1.sqrMagnitude;
  11. float f2 = v2.sqrMagnitude;
  12. Debug.Log("v1模长的平方值:" + f1 + " v2模长的平方值:" + f2);
  13. if(f1 == f2){
  14. Debug.Log("向量v1和v2的模长一样大!");
  15. }
  16. else if (f1 > f2)
  17. {
  18. Debug.Log("向量v1的模长比较大!");
  19. }else{
  20. Debug.Log("向量v2的模长比较大!");
  21. }
  22. }
  23. }

SqrMagnitude

Unity API 解析 (陈泉宏著)的更多相关文章

  1. Unity API 解析(13)—— Vector3 类

    三维向量或三维坐标点 normalized —— 单位化向量 返回方向相同模长为1的向量 sqrMagnitude —— 模长平方 Scale —— 向量缩放 Angle —— 两向量夹角 Cross ...

  2. java微信开发API解析(二)-获取消息和回复消息

    java微信开发API解析(二)-获取消息和回复消息 说明 * 本演示样例依据微信开发文档:http://mp.weixin.qq.com/wiki/home/index.html最新版(4/3/20 ...

  3. 源生API解析XML文档与dom4j解析XML文档

    一.XML语言 XML是一种可扩展的标记语言,是一种强类型的语言,类似HTML(超文本标记语言,是一种弱类型的语言).XML是一种通用的数据交换格式(关系型数据库),综上所诉:XML可以传输数据,也可 ...

  4. 使用JAVA API 解析ORC File

    使用JAVA API 解析ORC File orc File 的解析过程中,使用FileInputFormat的getSplits(conf, 1)函数, 然后使用 RecordReaderreade ...

  5. Activiti学习笔记5 — 常用API解析

    常用API解析: 一.ProcessEngineConfiguration 流程引擎配置对象(配置数据库连接4个大配置和建表策略) 二.ProcessEngine          流程引擎核心对象( ...

  6. JavaScript 对象所有API解析【2020版】

    JavaScript 对象所有API解析[2020版] 写于 2019年08月20日,虽然是2019年写的文章,但现在2020年依旧不过时,现在补充了2019年新增的ES10 Object.fromE ...

  7. Winform实现用多线程、百度地图API解析某公司的物理地址

    前言 作为一个很挫的C#新手总喜欢自己写点儿不着边际的东西,本人是个新手加菜鸟,写B/S的,工作中,任务完成了,空闲下来,总想继续学点儿什么,由此触发了本篇文章了.个人一直认为,.NET中,C/S所要 ...

  8. unity文件解析以及版本控制

    刚开始使用unity做开发时,拿到一个范例工程先上传SVN,之后再自己做一些修改后,发现有非常多文件都有变化,这才知道有很多本地生成的文件,是不用上传的,但是不知道哪些才是需要共用的.之后又困扰于修改 ...

  9. Unity各平台内置宏定义

    属性 方法 UNITY_EDITOR #define directive for calling Unity Editor scripts from your game code. UNITY_EDI ...

随机推荐

  1. table-cell 布局

    table-cell能实现段落文字相对于div的垂直居中: 将div设置为display:table-cell; *display:inline-block;text-align:center; ve ...

  2. 1085 PAT单位排行

    每次 PAT 考试结束后,考试中心都会发布一个考生单位排行榜.本题就请你实现这个功能. 输入格式: 输入第一行给出一个正整数 N(≤10​^5​​),即考生人数.随后 N 行,每行按下列格式给出一个考 ...

  3. DevExpress v18.1新版亮点——Reporting篇(一)

    用户界面套包DevExpress v18.1日前终于正式发布,本站将以连载的形式为大家介绍各版本新增内容.本文将介绍了DevExpress Reporting v18.1 的新功能,快来下载试用新版本 ...

  4. system v ipc的标识符ID

    system v ipc对象是靠标识符ID来识别和操作的,具有系统唯一性.意思就是说,该ID是操作系统内的全局变量,只要具有权限,任何进程都可以通过标识符进行进程间的通信.获取标识符ID的函数为int ...

  5. L256 翻译

    Should work be placed among the causes of happiness or be regarded as a burden? Much work isexceedin ...

  6. 【转】CEF3加载网页---多字节字符集和UNICODE字符集

    static char* MBSCToCEF(const char* mbcsStr) { wchar_t* wideStr; char* utf8Str; int charLen; charLen ...

  7. LVS原理详解(3种工作方式8种调度算法)

    一.集群简介 什么是集群 计算机集群简称集群是一种计算机系统,它通过一组松散集成的计算机软件和/或硬件连接起来高度紧密地协作完成计算工作.在某种意义上,他们可以被看作是一台计算机.集群系统中的单个计算 ...

  8. RIP路由协议(一)

    实验要求:使用RIPv2配置路由器,使路由器能接收到所有的路由条目 拓扑如下: 配置如下: R1enable 进入特权模式configure terminal 进入全局模式interface s0/0 ...

  9. 机器学习: 共轭梯度算法(PCG)

    今天介绍数值计算和优化方法中非常有效的一种数值解法,共轭梯度法.我们知道,在解大型线性方程组的时候,很少会有一步到位的精确解析解,一般都需要通过迭代来进行逼近,而 PCG 就是这样一种迭代逼近算法. ...

  10. Opencv-Python 图像透视变换cv2.warpPerspective

    # -*- coding:utf-8 -*- import cv2 import numpy as np import sys img = cv2.imread('test.jpg') # cv2.i ...