Unity API 解析 (陈泉宏著)
1 Application类
- using UnityEngine;
- using System.Collections;
- public class DataPath_ts : MonoBehaviour
- {
- void Start()
- {
- //四种不同的path,都为只读
- //dataPath和streamingAssetsPath的路径位置一般是相对程序的安装目录位置
- //persistentDataPath和temporaryCachePath的路径位置一般是相对所在系统的固定位置
- Debug.Log("dataPath:" + Application.dataPath);
- Debug.Log("persistentDataPath:" + Application.persistentDataPath);
- Debug.Log("streamingAssetsPath:" + Application.streamingAssetsPath);
- Debug.Log("temporaryCachePath:" + Application.temporaryCachePath);
- }
- }
DataPath
- using UnityEngine;
- using System.Collections;
- public class LoadedLevel_ts : MonoBehaviour
- {
- void Start()
- {
- //返回当前场景的索引值
- Debug.Log("loadedLevel:" + Application.loadedLevel);
- //返回当前场景的名字
- Debug.Log("loadedLevelName:" + Application.loadedLevelName);
- //是否有场景正在被加载
- Debug.Log("isLoadingLevel:" + Application.isLoadingLevel);
- //返回游戏中可被加载的场景数量
- Debug.Log("levelCount:" + Application.levelCount);
- //返回当前游戏的运行平台
- Debug.Log("platform:" + Application.platform);
- //当前游戏是否正在运行
- Debug.Log("isPlaying:" + Application.isPlaying);
- //当前游戏是否处于Unity编辑模式
- Debug.Log("isEditor:" + Application.isEditor);
- }
- }
LoadedLevel
- using UnityEngine;
- using System.Collections;
- public class CaptureScreenshot_ts : MonoBehaviour
- {
- ;
- void Update()
- {
- )
- {
- //默认值,不放大
- Application.CaptureScreenshot();
- }
- )
- {
- //放大系数为1,即不放大
- Application.CaptureScreenshot();
- }
- else
- {
- //放大系数为2,即放大2倍
- Application.CaptureScreenshot();
- }
- tp++;
- }
- }
CaptureScreenshot
- using UnityEngine;
- using System.Collections;
- public class Capture_Use_ts : MonoBehaviour
- {
- //td:用来指向屏幕截图
- Texture2D td = null;
- //txt_bg:用来指向文本输入的背景图片
- //可以指向一张纯色的图片,也可以自定义一个纯色的背景
- //本程序自定义了一个纯色的背景
- Texture2D txt_bg;
- //txt_w和txt_h用来记录文本框的宽度和高度
- int txt_w, txt_h;
- //my_save_path:用来记录截图的保存路径
- string my_save_path = "";
- //show_txt:用来记录输入的文本
- string show_txt = "在此输入";
- //my_colors:用来记录文本输入框的纹理颜色
- Color[] my_colors;
- //_w和_h用来记录my_colors的宽度和高度
- int _w, _h;
- //step:用来记录当前状态,step共有3种状态:
- //step=0时,是等待状态,等待在文本框中输入文本
- //step=1时,即点击“确定”按钮后,生成截图并保存
- //step=2时,读取截图信息
- //step=3时,是对读取的截图信息进行有选择的提取,并生成想要展示的内容
- ;
- //go:用来指向拼字所用物体对象
- public GameObject go;
- //gos:用来记录所有的go对象
- GameObject[] gos;
- //gos_max用来记录gos的最大容量
- int gos_max;
- //gos_cur用来记录gos当前使用值
- ;
- //is_show:用来记录图像矩阵中某个点是否需要展示物体
- bool[,] is_show;
- void Start()
- {
- //初始化文本框的宽度和高度
- txt_w = ;
- txt_h = ;
- //初始化截取区间的大小,为了避免边界识别错误,其值应该比文本框的宽度和高度少几个像素
- _w = txt_w;
- _h = txt_h;
- _w -= ;
- _h -= ;
- //自定义txt_bg纹理
- txt_bg = new Texture2D(txt_w, txt_h);
- Color[] tdc = new Color[txt_w * txt_h];
- ; i < txt_w * txt_h; i++)
- {
- //所用像素点颜色应相同
- tdc[i] = Color.white;
- }
- txt_bg.SetPixels(, , txt_w, txt_h, tdc);
- is_show = new bool[_h, _w];
- //初始化gos_max,其值大小为_w * _h的三分之一在一般情况下就够用了
- gos_max = _w * _h / ;
- //实例化gos,使其随机分布_w和_h的区间内
- gos = new GameObject[gos_max];
- ; i < gos_max; i++)
- {
- gos[i] = (GameObject)Instantiate(go, new Vector3(Random.value * _w, Random.value * _h, 10.0f), Quaternion.identity);
- gos[i].GetComponent<Capture_Use_Sub_ts>().toward = gos[i].transform.position;
- }
- //存储初始界面截图
- my_save_path = Application.persistentDataPath;
- Application.CaptureScreenshot(my_save_path + "/ts02.png");
- }
- void Update()
- {
- switch (step)
- {
- :
- break;
- :
- step = ;
- //截图并保存
- my_save_path = Application.persistentDataPath;
- Application.CaptureScreenshot(my_save_path + "/ts02.png");
- //给电脑一点儿时间用来保存新截取的图片
- Invoke("My_WaitForSeconds", 0.4f);
- Debug.Log(my_save_path);
- break;
- :
- //由于在读取截图纹理的时候,一帧之内可能无法读完
- //所以需要step=0,避免逻辑出现混乱
- step = ;
- //读取截图信息
- my_save_path = Application.persistentDataPath;
- StartCoroutine(WaitLoad(my_save_path + "/ts02.png"));
- break;
- :
- //在计算并生成展示信息的时候,一帧之内可能无法完成
- //所以需要step=0,避免逻辑出现混乱
- step = ;
- //计算并生成展示信息
- Cum();
- break;
- }
- }
- //计算并生成展示信息
- void Cum()
- {
- if (td != null)
- {
- float ft;
- //ft:用来记录文本框左下角像素的R通道值,用来作为后面的参照
- ft = td.GetPixel(, td.height - _h).r;
- //截取文本框纹理信息
- //需要注意的是,纹理坐标系和GUI坐标系不同
- //纹理坐标系以坐下角为原点,而GUI坐标系以左上角为原点
- //以2为x方向起点是为了避免截图边缘的痕迹
- my_colors = td.GetPixels(, td.height - _h, _w, _h);
- int l = my_colors.Length;
- Debug.Log("length: " + l);
- //通过遍历my_colors的R值,将其与ft比较来确定是否需要展示物体
- ; i < l; i++)
- {
- is_show[i / _w, i % _w] = my_colors[i].r == ft ? false : true;
- }
- //根据is_show的值排列gos中物体的位置
- ; i < _h; i++)
- {
- ; j < _w; j++)
- {
- if (is_show[i, j])
- {
- if (gos_cur < gos_max)
- {
- gos[gos_cur].GetComponent<Capture_Use_Sub_ts>().toward = new Vector3(j, i, 0.0f);
- gos[gos_cur].SetActive(true);
- gos_cur++;
- }
- //当当前gos数量不够用时需要扩充gos的容量
- else
- {
- Debug.Log("容量过小");
- int temps = gos_max;
- //将gos容量扩大1.5倍
- gos_max = (int)(gos_max * 1.5f);
- GameObject[] tps = new GameObject[gos_max];
- ; k < temps; k++)
- {
- tps[k] = gos[k];
- }
- for (int k = temps; k < gos_max; k++)
- {
- tps[k] = (GameObject)Instantiate(go, new Vector3(Random.value * _h, Random.value * _w, 10.0f), Quaternion.identity);
- tps[k].GetComponent<Capture_Use_Sub_ts>().toward = tps[k].transform.position;
- }
- gos = new GameObject[gos_max];
- gos = tps;
- gos[gos_cur].GetComponent<Capture_Use_Sub_ts>().toward = new Vector3(j, i, 0.0f);
- gos[gos_cur].SetActive(true);
- gos_cur++;
- }
- }
- }
- }
- //隐藏gos中未曾用到的物体
- for (int k = gos_cur; k < gos_max; k++)
- {
- gos[k].SetActive(false);
- }
- }
- }
- //绘制界面
- void OnGUI()
- {
- //绘制纹理作为TextField的背景
- GUI.DrawTexture(new Rect(0.0f, 0.0f, txt_w, txt_h), txt_bg);
- GUIStyle gs = new GUIStyle();
- gs.fontSize = ;
- show_txt = GUI.TextField(, gs);
- , , , ), "确定"))
- {
- //取消在TextField中的焦点
- GUI.FocusControl(null);
- //重置gos_cur的值
- gos_cur = ;
- step = ;
- }
- //程序退出
- , , , ), "退出"))
- {
- Application.Quit();
- }
- }
- //加载图片
- IEnumerator WaitLoad(string fileName)
- {
- WWW wwwTexture = new WWW("file://" + fileName);
- Debug.Log(wwwTexture.url);
- yield return wwwTexture;
- td = wwwTexture.texture;
- step = ;
- }
- //进入步骤2
- void My_WaitForSeconds()
- {
- step = ;
- }
- }
Capture_Use
- using UnityEngine;
- using System.Collections;
- public class Capture_Use_Sub_ts : MonoBehaviour
- {
- //物体移动的目标位置
- public Vector3 toward;
- //物体移动时间
- float delays;
- void Start()
- {
- //获取一个随机值
- delays = Random.Range(2.0f, 4.0f);
- }
- void Update()
- {
- //通过更改物体位置来达到物体运动的效果
- transform.position = Vector3.MoveTowards(transform.position, toward, delays);
- }
- }
Capture_Use_Sub
- using UnityEngine;
- using System.Collections;
- public class RegisterLogCallback_ts : MonoBehaviour
- {
- string output = "";//日志输出信息
- string stack = "";//堆栈跟踪信息
- string logType = "";//日志类型
- ;
- //打印日志信息
- void Update()
- {
- Debug.Log("stack:" + stack);
- Debug.Log("logType:" + logType);
- Debug.Log("tp:"+(tp++));
- Debug.Log("output:" + output);
- }
- void OnEnable()
- {
- //注册委托
- Application.RegisterLogCallback(MyCallback);
- }
- void OnDisable()
- {
- //取消委托
- Application.RegisterLogCallback(null);
- }
- //委托方法
- //方法名字可以自定义,但方法的参数类型要符合Application.LogCallback中的参数类型
- void MyCallback(string logString, string stackTrace, LogType type)
- {
- output = logString;
- stack = stackTrace;
- logType = type.ToString();
- }
- }
RegisterLogCallback
2 Camera类
- using UnityEngine;
- using System.Collections;
- public class Aspect_ts : MonoBehaviour
- {
- void Start()
- {
- //camera.aspect的默认值即为当前硬件的aspect值
- Debug.Log("camera.aspect的默认值:" + camera.aspect);
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "aspect=1.0f"))
- {
- camera.ResetAspect();
- camera.aspect = 1.0f;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "aspect=2.0f"))
- {
- camera.ResetAspect();
- camera.aspect = 2.0f;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "aspect还原默认值"))
- {
- camera.ResetAspect();
- }
- }
- }
Aspect
- using UnityEngine;
- using System.Collections;
- public class CameraToWorldMatrix_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log("Camera旋转前位置:" + transform.position);
- Matrix4x4 m = camera.cameraToWorldMatrix;
- //v3的值为沿着Camera局部坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
- Vector3 v3 = m.MultiplyPoint(Vector3.forward * 5.0f);
- //v4的值为沿着Camera世界坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
- Vector3 v4 = m.MultiplyPoint(transform.forward * 5.0f);
- //打印v3、v4
- Debug.Log("旋转前,v3坐标值:" + v3);
- Debug.Log("旋转前,v4坐标值:" + v4);
- transform.Rotate(Vector3.up * 90.0f);
- Debug.Log("Camera旋转后位置:" + transform.position);
- m = camera.cameraToWorldMatrix;
- //v3的值为沿着Camera局部坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
- v3 = m.MultiplyPoint(Vector3.forward * 5.0f);
- //v3的值为沿着Camera世界坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置
- v4 = m.MultiplyPoint(transform.forward * 5.0f);
- //打印v3、v4
- Debug.Log("旋转后,v3坐标值:" + v3);
- Debug.Log("旋转后,v4坐标值:" + v4);
- }
- }
CameraToWorldMatrix
- using UnityEngine;
- using System.Collections;
- public class CullingMask_ts : MonoBehaviour
- {
- void OnGUI()
- {
- //默认CullingMask=-1,即渲染任何层
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "CullingMask=-1"))
- {
- camera.cullingMask = -;
- }
- //不渲染任何层
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "CullingMask=0"))
- {
- camera.cullingMask = ;
- }
- //仅渲染第0层
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "CullingMask=1<<0"))
- {
- camera.cullingMask = << ;
- }
- //仅渲染第8层
- if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "CullingMask=1<<8"))
- {
- camera.cullingMask = << ;
- }
- //渲染第8层与第0层
- if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "CullingMask=0&&8"))
- {
- //注:不可大意写成camera.cullingMask = 1 << 8+1;或
- //camera.cullingMask = 1+1<<8 ;因为根据运算符优先次序其分别等价于:
- //camera.cullingMask = 1 << (8+1)和camera.cullingMask = (1+1)<<8;
- camera.cullingMask = ( << ) + ;
- }
- }
- }
CullingMask
- using UnityEngine;
- using System.Collections;
- public class EventMask_ts : MonoBehaviour
- {
- bool is_rotate = false;//控制物体旋转
- public Camera c;//指向场景中摄像机
- //记录摄像机的eventMask值,可以在程序运行时在Inspector面板中修改其值的大小
- ;
- //记录当前物体的层
- int layer_now;
- int tp;//记录2的layer次方的值
- int ad;//记录与运算(&)的结果
- string str = null;
- void Update()
- {
- //记录当前对象的层,可以在程序运行时在Inspector面板中选择不同的层
- layer_now = gameObject.layer;
- //求2的layer_now次方的值
- tp = (int)Mathf.Pow(2.0f, layer_now);
- //与运算(&)
- ad = eventMask_now & tp;
- c.eventMask = eventMask_now;
- //当is_rotate为true时旋转物体
- if (is_rotate)
- {
- transform.Rotate(Vector3.up * 15.0f * Time.deltaTime);
- }
- }
- //当鼠标左键按下时,物体开始旋转
- void OnMouseDown()
- {
- is_rotate = true;
- }
- //当鼠标左键抬起时,物体结束旋转
- void OnMouseUp()
- {
- is_rotate = false;
- }
- void OnGUI()
- {
- GUI.Label(new Rect(10.0f, 10.0f, 300.0f, 45.0f), "当前对象的layer值为:" + layer_now + " , 2的layer次方的值为" + tp);
- GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前摄像机eventMask的值为:" + eventMask_now);
- GUI.Label(new Rect(10.0f, 110.0f, 500.0f, 45.0f), "根据算法,当eventMask的值与" + tp + "进行与运算(&)后, 若结果为" + tp + ",则物体相应OnMousexxx方法,否则不响应!");
- if (ad == tp)
- {
- str = " ,所以物体会相应OnMouseXXX方法!";
- }
- else
- {
- str = " ,所以物体不会相应OnMouseXXX方法!";
- }
- GUI.Label(new Rect(10.0f, 160.0f, 500.0f, 45.0f), "而当前eventMask与" + tp + "进行与运算(&)的结果为" + ad + str);
- }
- }
EventMask
- using UnityEngine;
- using System.Collections;
- public class LayerCullDistances_ts : MonoBehaviour
- {
- public Transform cb1;
- void Start()
- {
- //定义大小为32的一维数组,用来存储所有层的剔除距离
- ];
- //设置第9层的剔除距离
- distances[] = Vector3.Distance(transform.position, cb1.position);
- //将数组赋给摄像机的layerCullDistances
- camera.layerCullDistances = distances;
- }
- void Update()
- {
- //摄像机远离物体
- transform.Translate(transform.right * Time.deltaTime);
- }
- }
LayerCullDistances
- using UnityEngine;
- using System.Collections;
- public class layerCullSpherical_ts : MonoBehaviour
- {
- public Transform cb1, cb2, cb3;
- void Start()
- {
- //定义大小为32的一维数组,用来存储所有层的剔除距离
- ];
- //设置第9层的剔除距离
- distances[] = Vector3.Distance(transform.position, cb1.position);
- //将数组赋给摄像机的layerCullDistances
- camera.layerCullDistances = distances;
- //打印出三个物体距离摄像机的距离
- Debug.Log("Cube1距离摄像机的距离:" + Vector3.Distance(transform.position, cb1.position));
- Debug.Log("Cube2距离摄像机的距离:" + Vector3.Distance(transform.position, cb2.position));
- Debug.Log("Cube3距离摄像机的距离:" + Vector3.Distance(transform.position, cb3.position));
- }
- void OnGUI()
- {
- //使用球形距离剔除
- if (GUI.Button(new Rect(10.0f, 10.0f, 180.0f, 45.0f), "use layerCullSpherical"))
- {
- camera.layerCullSpherical = true;
- }
- //取消球形距离剔除
- if (GUI.Button(new Rect(10.0f, 60.0f, 180.0f, 45.0f), "unuse layerCullSpherical"))
- {
- camera.layerCullSpherical = false;
- }
- }
- }
layerCullSpherical
- using UnityEngine;
- using System.Collections;
- public class orthographic_ts : MonoBehaviour
- {
- float len = 5.5f;
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "正交投影"))
- {
- camera.orthographic = true;
- len = 5.5f;
- }
- if (GUI.Button(new Rect(150.0f, 10.0f, 120.0f, 45.0f), "透视投影"))
- {
- camera.orthographic = false;
- len = 60.0f;
- }
- if (camera.orthographic)
- {
- //正交投影模式下,物体没有远大近小的效果,
- //orthographicSize的大小无限制,当orthographicSize为负数时视口的内容会颠倒,
- //orthographicSize的绝对值为摄像机视口的高度值,即上下两条边之间的距离
- len = GUI.HorizontalSlider(new Rect(10.0f, 60.0f, 300.0f, 45.0f), len, -20.0f, 20.0f);
- camera.orthographicSize = len;
- }
- else
- {
- //透视投影模式下,物体有远大近小的效果,
- //fieldOfViewd的取值范围为1.0-179.0
- len = GUI.HorizontalSlider(new Rect(10.0f, 60.0f, 300.0f, 45.0f), len, 1.0f, 179.0f);
- camera.fieldOfView = len;
- }
- //实时显示len大小
- GUI.Label(new Rect(320.0f, 60.0f, 120.0f, 45.0f), len.ToString());
- }
- }
orthographic
- using UnityEngine;
- using System.Collections;
- public class PixelRect_ts : MonoBehaviour
- {
- ;
- float temp_x = 0.0f, temp_y = 0.0f;
- void Update()
- {
- //Screen.width和Screen.height为模拟硬件屏幕的宽高值,
- //其返回值不随camera.pixelWidth和camera.pixelHeight的改变而改变
- Debug.Log("Screen.width:" + Screen.width);
- Debug.Log("Screen.height:" + Screen.height);
- Debug.Log("pixelWidth:" + camera.pixelWidth);
- Debug.Log("pixelHeight:" + camera.pixelHeight);
- //通过改变Camera的坐标位置而改变视口的区间
- )
- {
- if (camera.pixelWidth > 1.0f)
- {
- temp_x += Time.deltaTime * 20.0f;
- }
- //取消以下注释察看平移状况
- //if (camera.pixelHeight > 1.0f)
- //{
- // temp_y += Time.deltaTime * 20.0f;
- //}
- camera.pixelRect = new Rect(temp_x, temp_y, camera.pixelWidth, camera.pixelHeight);
- }
- //通过改变Camera的视口宽度和高度来改变视口的区间
- )
- {
- if (camera.pixelWidth > 1.0f)
- {
- temp_x = camera.pixelWidth - Time.deltaTime * 20.0f;
- }
- //取消以下注释察看平移状况
- //if (camera.pixelHeight > 1.0f)
- //{
- // temp_y = camera.pixelHeight - Time.deltaTime * 20.0f;
- //}
- camera.pixelRect = , , temp_x, temp_y);
- }
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "视口改变方式1"))
- {
- camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
- which_change = ;
- temp_x = 0.0f;
- temp_y = 0.0f;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "视口改变方式2"))
- {
- camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
- which_change = ;
- temp_x = 0.0f;
- temp_y = camera.pixelHeight;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "视口还原"))
- {
- camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
- which_change = -;
- }
- }
- }
PixelRect
- using UnityEngine;
- using System.Collections;
- public class ProjectionMatrix_ts : MonoBehaviour
- {
- public Transform sp, cb;
- public Matrix4x4 originalProjection;
- float q=0.1f;//晃动振幅
- float p=1.5f;//晃动频率
- ;
- void Start()
- {
- //记录原始投影矩阵
- originalProjection = camera.projectionMatrix;
- }
- void Update()
- {
- sp.RotateAround(cb.position, cb.up, 45.0f * Time.deltaTime);
- Matrix4x4 pr = originalProjection;
- switch (which_change)
- {
- :
- break;
- :
- //绕摄像机X轴晃动
- pr.m11 += Mathf.Sin(Time.time * p) * q;
- break;
- :
- //绕摄像机Y轴晃动
- pr.m01 += Mathf.Sin(Time.time * p) * q;
- break;
- :
- //绕摄像机Z轴晃动
- pr.m10 += Mathf.Sin(Time.time * p) * q;
- break;
- :
- //绕摄像机左右移动
- pr.m02 += Mathf.Sin(Time.time * p) * q;
- break;
- :
- //摄像机视口放缩运动
- pr.m00 += Mathf.Sin(Time.time * p) * q;
- break;
- }
- //设置Camera的变换矩阵
- camera.projectionMatrix = pr;
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "绕摄像机X轴晃动"))
- {
- camera.ResetProjectionMatrix();
- which_change = ;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "绕摄像机Y轴晃动"))
- {
- camera.ResetProjectionMatrix();
- which_change = ;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "绕摄像机Z轴晃动"))
- {
- camera.ResetProjectionMatrix();
- which_change = ;
- }
- if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "绕摄像机左右移动"))
- {
- camera.ResetProjectionMatrix();
- which_change = ;
- }
- if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "视口放缩运动"))
- {
- camera.ResetProjectionMatrix();
- which_change = ;
- }
- }
- }
ProjectionMatrix
- using UnityEngine;
- using System.Collections;
- public class Rect_ts : MonoBehaviour
- {
- ;
- float temp_x = 0.0f, temp_y = 0.0f;
- void Update()
- {
- //视口平移
- )
- {
- if (camera.rect.x < 1.0f)
- {
- //沿着X轴平移
- temp_x = camera.rect.x + Time.deltaTime * 0.2f;
- }
- //取消下面注释察看平移的变化
- //if (camera.rect.y< 1.0f)
- //{
- //沿着Y轴平移
- // temp_y = camera.rect.y + Time.deltaTime * 0.2f;
- //}
- camera.rect = new Rect(temp_x, temp_y, camera.rect.width, camera.rect.height);
- }
- //视口放缩
- )
- {
- if (camera.rect.width > 0.0f)
- {
- //沿着X轴放缩
- temp_x = camera.rect.width - Time.deltaTime * 0.2f;
- }
- if (camera.rect.height > 0.0f)
- {
- //沿着Y轴放缩
- temp_y = camera.rect.height - Time.deltaTime * 0.2f;
- }
- camera.rect = new Rect(camera.rect.x, camera.rect.y, temp_x, temp_y);
- }
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "视口平移"))
- {
- //重置视口
- camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
- which_change = ;
- temp_y = 0.0f;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "视口放缩"))
- {
- camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
- which_change = ;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "视口还原"))
- {
- camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
- which_change = -;
- }
- }
- }
Rect
- using UnityEngine;
- using System.Collections;
- public class renderingPath_ts : MonoBehaviour
- {
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "UsePlayerSettings"))
- {
- camera.renderingPath = RenderingPath.UsePlayerSettings;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 120.0f, 45.0f), "VertexLit"))
- {
- camera.renderingPath = RenderingPath.VertexLit;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 120.0f, 45.0f), "Forward"))
- {
- camera.renderingPath = RenderingPath.Forward;
- }
- if (GUI.Button(new Rect(10.0f, 160.0f, 120.0f, 45.0f), "DeferredLighting"))
- {
- camera.renderingPath = RenderingPath.DeferredLighting;
- }
- }
- }
renderingPath
- using UnityEngine;
- using System.Collections;
- public class Target_ts : MonoBehaviour {
- public Transform ts;
- void Update () {
- transform.RotateAround(ts.position,ts.up,30.0f*Time.deltaTime);
- }
- }
Target
- using UnityEngine;
- using System.Collections;
- public class WorldToCameraMatrix_ts : MonoBehaviour
- {
- public Camera c_test;
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "更改变换矩阵"))
- {
- //使用c_test的变换矩阵
- camera.worldToCameraMatrix = c_test.worldToCameraMatrix;
- //也可使用如下代码实现同样功能
- // camera.CopyFrom(c_test);
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "重置变换矩阵"))
- {
- camera.ResetWorldToCameraMatrix();
- }
- }
- }
WorldToCameraMatrix
- using UnityEngine;
- using System.Collections;
- public class RenderToCubemap_ts : MonoBehaviour
- {
- public Cubemap cp;
- void Start()
- {
- camera.RenderToCubemap(cp);
- }
- }
RenderToCubemap
- using UnityEngine;
- using System.Collections;
- public class RenderWithShader_ts : MonoBehaviour
- {
- bool is_use = false;
- void OnGUI()
- {
- if (is_use)
- {
- //使用高光shader:Specular来渲染Camera
- camera.RenderWithShader(Shader.Find("Specular"), "RenderType");
- }
- if (GUI.Button(new Rect(10.0f, 10.0f, 300.0f, 45.0f), "使用RenderWithShader启用高光"))
- {
- //RenderWithShader每调用一次只渲染一帧,所以不可将其直接放到这儿
- //camera.RenderWithShader(Shader.Find("Specular"), "RenderType");
- is_use = true;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "使用SetReplacementShader启用高光"))
- {
- //SetReplacementShader方法用来替换已有shader,调用一次即可
- camera.SetReplacementShader(Shader.Find("Specular"), "RenderType");
- is_use = false;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "关闭高光"))
- {
- camera.ResetReplacementShader();
- is_use = false;
- }
- }
- }
RenderWithShader
- using UnityEngine;
- using System.Collections;
- public class ScreenPointToRay_ts : MonoBehaviour
- {
- Ray ray;
- RaycastHit hit;
- Vector3 v3 = new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 0.0f);
- Vector3 hitpoint = Vector3.zero;
- void Update()
- {
- //射线沿着屏幕X轴从左向右循环扫描
- v3.x = v3.x >= Screen.width ? 0.0f : v3.x + 1.0f;
- //生成射线
- ray = camera.ScreenPointToRay(v3);
- if (Physics.Raycast(ray, out hit, 100.0f))
- {
- //绘制线,在Scene视图中可见
- Debug.DrawLine(ray.origin, hit.point, Color.green);
- //输出射线探测到的物体的名称
- Debug.Log("射线探测到的物体名称:" + hit.transform.name);
- }
- }
- }
ScreenPointToRay
- using UnityEngine;
- using System.Collections;
- public class ScreenToViewportPoint_ts : MonoBehaviour
- {
- void Start()
- {
- transform.position = new Vector3(0.0f, 0.0f, 1.0f);
- transform.rotation = Quaternion.identity;
- //从屏幕的实际坐标点向视口的单位化比例值转换
- Debug.Log("1:" + camera.ScreenToViewportPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f)));
- //从视口的单位化比例值向屏幕的实际坐标点转换
- Debug.Log("2:" + camera.ViewportToScreenPoint(new Vector3(0.5f, 0.5f, 100.0f)));
- Debug.Log("屏幕宽:" + Screen.width + " 屏幕高:" + Screen.height);
- }
- }
ScreenToViewportPoint
- using UnityEngine;
- using System.Collections;
- public class ScreenToWorldPoint_ts : MonoBehaviour
- {
- void Start()
- {
- transform.position = new Vector3(0.0f, 0.0f, 1.0f);
- camera.fieldOfView = 60.0f;
- camera.aspect = 16.0f / 10.0f;
- //Z轴前方100处对应的屏幕的左下角的世界坐标值
- Debug.Log("1:" + camera.ScreenToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f)));
- //Z轴前方100处对应的屏幕的中间的世界坐标值
- Debug.Log("2:" + camera.ScreenToWorldPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f)));
- //Z轴前方100处对应的屏幕的右上角的世界坐标值
- Debug.Log("3:" + camera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 100.0f)));
- }
- }
ScreenToWorldPoint
- using UnityEngine;
- using System.Collections;
- public class SetTargetBuffers_ts : MonoBehaviour
- {
- //声明两个RendererTexture变量
- public RenderTexture RT_1, RT_2;
- public Camera c;//指定Camera
- void OnGUI()
- {
- //设置RT_1的buffer为摄像机c的渲染
- if (GUI.Button(new Rect(10.0f, 10.0f, 180.0f, 45.0f), "set target buffers"))
- {
- c.SetTargetBuffers(RT_1.colorBuffer, RT_1.depthBuffer);
- }
- //设置RT_2的buffer为摄像机c的渲染,此时RT_1的buffer变为场景中Camera1的渲染
- if (GUI.Button(new Rect(10.0f, 60.0f, 180.0f, 45.0f), "Reset target buffers"))
- {
- c.SetTargetBuffers(RT_2.colorBuffer, RT_2.depthBuffer);
- }
- }
- }
SetTargetBuffers
- using UnityEngine;
- using System.Collections;
- public class ViewportPointToRay_ts : MonoBehaviour
- {
- Ray ray;//射线
- RaycastHit hit;
- Vector3 v3 = new Vector3(0.5f, 0.5f, 0.0f);
- Vector3 hitpoint = Vector3.zero;
- void Update()
- {
- //射线沿着屏幕X轴从左向右循环扫描
- v3.x = v3.x >= 1.0f ? 0.0f : v3.x + 0.002f;
- //生成射线
- ray = camera.ViewportPointToRay(v3);
- if (Physics.Raycast(ray, out hit, 100.0f))
- {
- //绘制线,在Scene视图中可见
- Debug.DrawLine(ray.origin, hit.point, Color.green);
- //输出射线探测到的物体的名称
- Debug.Log("射线探测到的物体名称:" + hit.transform.name);
- }
- }
- }
ViewportPointToRay
- using UnityEngine;
- using System.Collections;
- public class ViewportToWorldPoint_ts : MonoBehaviour
- {
- void Start()
- {
- transform.position = new Vector3(1.0f, 0.0f, 1.0f);
- camera.fieldOfView = 60.0f;
- camera.aspect = 16.0f / 10.0f;
- //屏幕左下角
- Debug.Log("1:" + camera.ViewportToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f)));
- //屏幕中间
- Debug.Log("2:" + camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 100.0f)));
- //屏幕右上角
- Debug.Log("3:" + camera.ViewportToWorldPoint(new Vector3(1.0f, 1.0f, 100.0f)));
- }
- }
ViewportToWorldPoint
- using UnityEngine;
- using System.Collections;
- public class WorldToScreenPoint_ts : MonoBehaviour
- {
- public Transform cb, sp;
- public Texture2D t2;
- Vector3 v3 = Vector3.zero;
- float sg;
- void Start()
- {
- //记录屏幕高度
- sg = Screen.height;
- }
- void Update()
- {
- //sp绕着cb的Y轴旋转
- sp.RotateAround(cb.position, cb.up, 30.0f * Time.deltaTime);
- //获取sp在屏幕上的坐标点
- v3 = camera.WorldToScreenPoint(sp.position);
- }
- void OnGUI()
- {
- //绘制纹理
- GUI.DrawTexture(new Rect(0.0f, sg - v3.y, v3.x, sg), t2);
- }
- }
WorldToScreenPoint
- using UnityEngine;
- using System.Collections;
- public class WorldToViewportPoint_ts : MonoBehaviour
- {
- public Transform cb, sp;
- public Texture2D t2;
- Vector3 v3 = Vector3.zero;
- float sw, sh;
- void Start()
- {
- //记录屏幕的宽度和高度
- sw = Screen.width;
- sh = Screen.height;
- }
- void Update()
- {
- //物体sp始终绕cb的Y轴旋转
- sp.RotateAround(cb.position, cb.up, 30.0f * Time.deltaTime);
- //记录sp映射到屏幕上的比例值
- v3 = camera.WorldToViewportPoint(sp.position);
- }
- void OnGUI()
- {
- //绘制纹理,由于方法WorldToViewportPoint的返回值的y分量是从屏幕下方向上方递增的,
- //所以需要先计算1.0f - v3.y的值,然后再和sh相乘。
- GUI.DrawTexture(new Rect(0.0f, sh * (1.0f - v3.y), sw * v3.x, sh), t2);
- }
- }
WorldToViewportPoint
- using UnityEngine;
- using System.Collections;
- public class Compare_ts : MonoBehaviour
- {
- Vector3 v1;
- void Start()
- {
- v1 = transform.position;
- }
- void OnGUI()
- {
- //设置Camera视口宽高比例为2:1,点击此按钮后更改Game视图中不同的aspect值,
- //尽管Scene视图中Camera视口的宽高比会跟着改变,但实际Camera视口的内容依然是按照2:1
- //的比例所所获取的,不同的屏幕显示相同的内容会发生变形。
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Camera视口宽高比例2:1"))
- {
- camera.aspect = 2.0f;
- transform.position = v1;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Camera视口宽高比例1:2"))
- {
- camera.aspect = 0.5f;
- //更改Camera坐标,使被拉伸后的物体显示出来
- transform.position = new Vector3(v1.x, v1.y, 333.2f);
- }
- //恢复aspect的默认设置,即屏幕比例和Camera视口比例保持一致
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "使用Game面板中aspect的选择"))
- {
- camera.ResetAspect();
- transform.position = v1;
- }
- }
- }
Compare
3 GameObject类
- using UnityEngine;
- using System.Collections;
- public class ActiveSelf_ts : MonoBehaviour {
- public GameObject cube1, cube2, cube3;
- void Start () {
- //对cube2设置为false,其他设置为true
- cube1.SetActive(true);
- cube2.SetActive(false);
- cube3.SetActive(true);
- Debug.Log("activeSelf:");
- //尽管cube2被设置为false,但其子类cube3的activeSelf返回值仍然为true
- Debug.Log("cube1.activeSelf:" + cube1.activeSelf);
- Debug.Log("cube2.activeSelf:" + cube2.activeSelf);
- Debug.Log("cube3.activeSelf:" + cube3.activeSelf);
- Debug.Log("\nactiveInHierarchy:");
- //cube2和cube3的activeInHierarchy返回值都为false。
- Debug.Log("cube1.activeInHierarchy:" + cube1.activeInHierarchy);
- Debug.Log("cube2.activeInHierarchy:" + cube2.activeInHierarchy);
- Debug.Log("cube3.activeInHierarchy:" + cube3.activeInHierarchy);
- }
- }
ActiveSelf
- using UnityEngine;
- using System.Collections;
- public class Constructors_ts : MonoBehaviour {
- void Start () {
- //使用构造函数GameObject (name : String)
- GameObject g1 = new GameObject("G1");
- g1.AddComponent<Rigidbody>();
- //使用构造函数GameObject ()
- GameObject g2 = new GameObject();
- g2.AddComponent<FixedJoint>();
- //使用构造函数GameObject (name : String, params components : Type[])
- GameObject g3 = new GameObject("G3",typeof(MeshRenderer),typeof(Rigidbody),typeof(SpringJoint));
- Debug.Log("g1 name:" + g1.name + "\nPosition:" + g1.transform.position);
- Debug.Log("g2 name:" + g2.name + "\nPosition:" + g2.transform.position);
- Debug.Log("g3 name:" + g3.name + "\nPosition:" + g3.transform.position);
- }
- }
Constructors
- using UnityEngine;
- using System.Collections;
- public class GetComponent_ts : MonoBehaviour {
- void Start () {
- Debug.Log("以下是GetComponent的相关使用代码。\nGetComponent方法用来获取当前GameObject中符合Type类型的第一个组件。");
- //GetComponent (type : Type)
- Rigidbody rb = GetComponent(typeof(Rigidbody))as Rigidbody;
- Debug.Log("使用GetComponent (type : Type)获取Rigidbody:" + rb.GetInstanceID());
- //GetComponent.<T>()
- rb=GetComponent<Rigidbody>();
- Debug.Log("使用GetComponent.<T>()获取Rigidbody:" + rb.GetInstanceID());
- //GetComponent (type : String)
- rb = GetComponent("Rigidbody") as Rigidbody;
- Debug.Log("使用GetComponent (type : String)获取Rigidbody:" + rb.GetInstanceID());
- Debug.Log("以下是GetComponentInChildren的相关使用代码。\nGetComponentInChildren方法用来获取当前GameObject的所有子类中中符合Type类型的第一个组件。");
- //GetComponentInChildren (type : Type)
- rb = GetComponentInChildren(typeof(Rigidbody)) as Rigidbody;
- Debug.Log("使用GetComponentInChildren (type : Type)获取Rigidbody:" + rb.name);
- //GetComponentInChildren.<T> ()
- rb=GetComponentInChildren<Rigidbody>();
- Debug.Log("使用GetComponentInChildren.<T>()获取Rigidbody:" + rb.name);
- Debug.Log("以下是GetComponents的相关使用代码。\nGetComponents方法用来获取当前GameObject中符合Type类型的所有组件。");
- //GetComponents (type : Type)
- Component[] cjs = GetComponents(typeof(ConfigurableJoint)) as Component[];
- foreach(ConfigurableJoint cj in cjs){
- Debug.Log("使用GetComponents (type : Type)获取ConfigurableJoint:" + cj.GetInstanceID());
- }
- //GetComponents.<T> ()
- cjs = GetComponents<ConfigurableJoint>();
- foreach (ConfigurableJoint cj in cjs)
- {
- Debug.Log("使用GetComponents.<T>()获取ConfigurableJoint:" + cj.GetInstanceID());
- }
- Debug.Log("以下是GetComponentsInChildren的相关使用代码。\nGetComponentsInChildren方法用来获取当前GameObject的子类中符合Type类型的所有组件。");
- //GetComponentsInChildren(type: Type, includeInactive: boolean = false)
- cjs = GetComponentsInChildren(typeof(ConfigurableJoint), false) as Component[];
- foreach (ConfigurableJoint cj in cjs)
- {
- Debug.Log("使用GetComponentsInChildren(type: Type, false)获取ConfigurableJoint:" + cj.name);
- }
- cjs = GetComponentsInChildren(typeof(ConfigurableJoint), true) as Component[];
- foreach (ConfigurableJoint cj in cjs)
- {
- Debug.Log("使用GetComponentsInChildren(type: Type, true)获取ConfigurableJoint:" + cj.name);
- }
- //GetComponentsInChildren.<T> (includeInactive : boolean)
- cjs = GetComponentsInChildren<ConfigurableJoint>(true);
- foreach (ConfigurableJoint cj in cjs)
- {
- Debug.Log("使用GetComponentsInChildren.<T>(includeInactive : boolean)获取ConfigurableJoint:" + cj.name);
- }
- //GetComponentsInChildren.<T> ()
- cjs = GetComponentsInChildren<ConfigurableJoint>();
- foreach (ConfigurableJoint cj in cjs)
- {
- Debug.Log("使用GetComponentsInChildren.<T>()获取ConfigurableJoint:" + cj.name);
- }
- }
- }
GetComponent
- using UnityEngine;
- using System.Collections;
- public class SendMessage_ts : MonoBehaviour {
- void Start () {
- //向子类及自己发送信息
- //gameObject.BroadcastMessage("GetParentMessage",gameObject.name+":use BroadcastMessage send!");
- //向自己发送信息
- gameObject.SendMessage("GetSelfMessage",gameObject.name+":use SendMessage send!");
- ////向父类及自己发送信息
- //gameObject.SendMessageUpwards("GetChildrenMessage",gameObject.name+":use SendMessageUpwards send!");
- }
- //一个接受父类发送信息的方法
- private void GetParentMessage(string str){
- Debug.Log(gameObject.name + "收到父类发送的消息:" + str);
- }
- //一个接受自身发送信息的方法
- private void GetSelfMessage(string str)
- {
- Debug.Log(gameObject.name + "收到自身发送的消息:" + str);
- }
- //一个接受子类发送信息的方法
- private void GetChildrenMessage(string str)
- {
- Debug.Log(gameObject.name + "收到子类发送的消息:" + str);
- }
- }
SendMessage
- using UnityEngine;
- using System.Collections;
- public class CreatePrimitive_ts : MonoBehaviour
- {
- void Start()
- {
- //使用GameObject.CreatePrimitive方法创建GameObject
- GameObject g1 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
- g1.name = "G1";
- g1.tag = "sphere_Tag";
- //使用 AddComponent (className : String)方法添加组件
- g1.AddComponent("SpringJoint");
- //使用AddComponent (componentType : Type)方法添加组件
- g1.AddComponent(typeof(GUITexture));
- g1.transform.position = Vector3.zero;
- GameObject g2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
- g2.name = "G2";
- g2.tag = "sphere_Tag";
- //使用AddComponent.<T>()方法添加组件
- g2.AddComponent<Rigidbody>();
- g2.transform.position = 2.0f * Vector3.right;
- g2.GetComponent<Rigidbody>().useGravity = false;
- GameObject g3 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
- g3.name = "G1";
- g3.tag = "sphere_Tag";
- g3.transform.position = 4.0f * Vector3.right;
- //使用GameObject.Find类方法获取GameObject,返回符合条件的第一个对象
- Debug.Log("use Find:" + GameObject.Find("G1").transform.position);
- //使用GameObject.FindGameObjectWithTag类方法获取GameObject,返回符合条件的第一个对象
- Debug.Log("use FindGameObjectWithTag:" + GameObject.FindGameObjectWithTag("sphere_Tag").transform.position);
- //使用GameObject.FindGameObjectsWithTag类方法获取GameObject,返回符合条件的所有对象
- GameObject[] gos = GameObject.FindGameObjectsWithTag("sphere_Tag");
- foreach (GameObject go in gos)
- {
- Debug.Log("use FindGameObjectsWithTag:" + go.name + ":" + go.transform.position);
- }
- g3.transform.parent = g2.transform;
- g2.transform.parent = g1.transform;
- Debug.Log("use Find again1:" + GameObject.Find("G1").transform.position);
- //使用带"/"限定条件的方式查找GameObject,
- //此处返回的对象需其父类为G2,且G2的父类名为G1,
- //注意与上面不带"/"限定条件返回的对象的区别。
- Debug.Log("use Find again2:" + GameObject.Find("/G1/G2/G1").transform.position);
- }
- }
CreatePrimitive
- using UnityEngine;
- using System.Collections;
- public class BroadcastMessage_ts : MonoBehaviour
- {
- void Start()
- {
- gameObject.BroadcastMessage("GetParentMessage", gameObject.name + ":use BroadcastMessage send!");
- }
- private void GetParentMessage(string str)
- {
- Debug.Log(gameObject.name + "收到父类发送的消息:" + str);
- }
- private void GetSelfMessage(string str)
- {
- Debug.Log(gameObject.name + "收到自身发送的消息:" + str);
- }
- private void GetChildrenMessage(string str)
- {
- Debug.Log(gameObject.name + "收到子类发送的消息:" + str);
- }
- }
BroadcastMessage
- using UnityEngine;
- using System.Collections;
- public class GameObjectAndComponent_ts : MonoBehaviour {
- public GameObject sp;
- void Start () {
- //以下三种表达方式功能一样,都返回当前脚本所在GameObject对象中的Rigidbody组件
- Rigidbody rb1 = rigidbody;
- Rigidbody rb2 = GetComponent<Rigidbody>();
- Rigidbody rb3 = rigidbody.GetComponent<Rigidbody>();
- Debug.Log("rb1的InstanceID:" + rb1.GetInstanceID());
- Debug.Log("rb2的InstanceID:" + rb2.GetInstanceID());
- Debug.Log("rb3的InstanceID:" + rb3.GetInstanceID());
- //使用前置引用获取引用对象的Rigidbody组件
- Debug.Log("前置引用sp对象中Rigidbody的InstanceID:"+sp.GetComponent<Rigidbody>().GetInstanceID());
- }
- }
GameObjectAndComponent
- using UnityEngine;
- using System.Collections;
- public class SendMessageUpward_ts : MonoBehaviour {
- void Start () {
- gameObject.SendMessageUpwards("GetChildrenMessage", gameObject.name + ":use SendMessageUpwards send!");
- }
- private void GetParentMessage(string str)
- {
- Debug.Log(gameObject.name + "收到父类发送的消息:" + str);
- }
- private void GetSelfMessage(string str)
- {
- Debug.Log(gameObject.name + "收到自身发送的消息:" + str);
- }
- private void GetChildrenMessage(string str)
- {
- Debug.Log(gameObject.name + "收到子类发送的消息:" + str);
- }
- }
SendMessageUpward
4 HideFlags类
- using UnityEngine;
- using System.Collections;
- public class DontSave_ts : MonoBehaviour {
- public GameObject go;
- public Transform t;
- void Start()
- {
- //GameObject对象使用HideFlags.DontSave可以在新scene中被保留
- go.hideFlags = HideFlags.DontSave;
- GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
- Pl.hideFlags = HideFlags.DontSave;
- //不可以对GameObject的组件设置HideFlags.DontSave,否则无效
- Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
- tf.hideFlags = HideFlags.DontSave;
- //导入名为newScene_unity的新scene
- Application.LoadLevel("newScene2_unity");
- }
- }
DontSave
- using UnityEngine;
- using System.Collections;
- public class HideInHierarchy_ts : MonoBehaviour
- {
- public GameObject go, sub;
- public Transform t;
- void Awake()
- {
- //go、sub、gameObject为已存在对象,需在Awake方法中使用HideFlags.HideInHierarchy
- go.hideFlags = HideFlags.HideInHierarchy;
- sub.hideFlags = HideFlags.HideInHierarchy;
- gameObject.hideFlags = HideFlags.HideInHierarchy;
- }
- void Start()
- {
- //Pl、tf是在代码中创建的对象,可以在任何方法中使用HideFlags.HideInHierarchy
- GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
- Pl.hideFlags = HideFlags.HideInHierarchy;
- Transform tf = Instantiate(t, go.transform.position + , 0.0f, 0.0f), Quaternion.identity) as Transform;
- tf.hideFlags = HideFlags.HideInHierarchy;
- }
- }
HideInHierarchy
- using UnityEngine;
- using System.Collections;
- public class HideInInspector_td : MonoBehaviour {
- public GameObject go;
- public Transform t;
- void Start()
- {
- //go、gameObject、Pl都是GameObject对象,使用HideFlags.HideInInspector后,
- //其所有组件将在Inspector面板中隐藏,
- //但并不影响其子类在Inspector面板中的显示。
- go.hideFlags = HideFlags.HideInInspector;
- gameObject.hideFlags = HideFlags.HideInInspector;
- GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
- Pl.hideFlags = HideFlags.HideInInspector;
- //tf为Transform对象,使用HideFlags.HideInInspector后,
- //tf对应的GameObject的Transform组件将在Inspector面板中隐藏,
- //但GameObject的其他组件扔可在Inspector面板中显示。
- Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
- tf.hideFlags = HideFlags.HideInInspector;
- }
- }
HideInInspector
- using UnityEngine;
- using System.Collections;
- public class NewScene_ts : MonoBehaviour {
- void Start () {
- Debug.Log("这是NewScene!");
- //导入名为newScene_unity2的新scene
- Application.LoadLevel("newScene2_unity");
- }
- }
NewScene
- using UnityEngine;
- using System.Collections;
- public class NewScene2_ts : MonoBehaviour
- {
- GameObject cube, plane;
- void Start()
- {
- Debug.Log("这是NewScene2!");
- }
- //当程序退出时用DestroyImmediate()销毁被HideFlags.DontSave标识的对象,
- //否则即使程序已经退出,被HideFlags.DontSave标识的对象依然在Hierarchy面板中,
- //即每运行一次程序就会产生多余对象,造成内存泄漏。
- void OnApplicationQuit()
- {
- cube = GameObject.Find("Cube0");
- plane = GameObject.Find("Plane");
- if (cube)
- {
- Debug.Log("Cube0 DestroyImmediate");
- DestroyImmediate(cube);
- }
- if (plane)
- {
- Debug.Log("Plane DestroyImmediate");
- DestroyImmediate(plane);
- }
- }
- }
NewScene2
- using UnityEngine;
- using System.Collections;
- public class NotEditable_ts : MonoBehaviour {
- public GameObject go;
- public Transform t;
- void Start()
- {
- //GameObject对象使用HideFlags.NotEditable可以使得GameObject的
- //所有组件在Inspector面板中都处于不可编辑状态。
- //GameObject对象被HideFlags.NotEditable标识并不影响其子类的可编辑性。
- go.hideFlags = HideFlags.NotEditable;
- GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane);
- Pl.hideFlags = HideFlags.NotEditable;
- //对于GameObject的某个组件单独使用HideFlags.NotEditable,
- //只会使得当前组件不可编辑,但GameObject的其他组件扔可编辑。
- t.hideFlags = HideFlags.NotEditable;
- Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform;
- tf.hideFlags = HideFlags.NotEditable;
- }
- }
NotEditable
5 Mathf类
- using UnityEngine;
- using System.Collections;
- public class Approximately_ts : MonoBehaviour {
- void Start () {
- float[] f={0.0f,2.0f,3.0f};
- ==/) ? true : false;
- bool b2 = Mathf.Approximately(1.0f, 10.0f/10.0f);
- Debug.Log("b1:"+b1);
- Debug.Log("b2:" + b2);
- Mathf.Min(f);
- }
- }
Approximately
- using UnityEngine;
- using System.Collections;
- public class Clamp_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log(, , ));
- Debug.Log(, , ));
- Debug.Log(, , ));
- //方法Clamp01的返回值范围为[0,1]
- Debug.Log("当value<0时:" + Mathf.Clamp01(-0.1f));
- Debug.Log("当0<value<1时:" + Mathf.Clamp01(0.5f));
- Debug.Log("当value>1时:" + Mathf.Clamp01(1.1f));
- }
- }
Clamp
- using UnityEngine;
- using System.Collections;
- public class ClosestPowerOfTwo_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log());
- Debug.Log());
- Debug.Log());
- }
- }
ClosestPowerOfTwo
- using UnityEngine;
- using System.Collections;
- public class DegAndRad_ts : MonoBehaviour {
- void Start () {
- //从角度到弧度转换常量
- Debug.Log("Mathf.Deg2Rad:" + Mathf.Deg2Rad);
- //从弧度到角度转换常量
- Debug.Log("Mathf.Rad2Deg:" + Mathf.Rad2Deg);
- }
- }
DegAndRad
- using UnityEngine;
- using System.Collections;
- public class DeltaAngle_ts : MonoBehaviour {
- void Start () {
- //1180=360*3+100,即求100和90之间的夹角
- Debug.Log(Mathf.DeltaAngle(, ));
- //-1130=-360*3-50,即求-50和90之间的夹角
- Debug.Log(Mathf.DeltaAngle(-, ));
- //-1200=-360*3-120,即求-120和90之间的夹角
- Debug.Log(Mathf.DeltaAngle(-, ));
- }
- }
DeltaAngle
- using UnityEngine;
- using System.Collections;
- public class Infinity_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log("0:" + Mathf.Infinity);
- Debug.Log("1:" + Mathf.Infinity / 10000.0f);
- Debug.Log("2:" + Mathf.Infinity / Mathf.Infinity);
- }
- }
Infinity
- using UnityEngine;
- using System.Collections;
- public class InverseLerp_ts : MonoBehaviour {
- void Start () {
- float f,from,to,v;
- from=-10.0f;
- to=30.0f;
- v=10.0f;
- f = Mathf.InverseLerp(from,to,v);
- Debug.Log("当0<f'<1时:"+f);
- v = -20.0f;
- f = Mathf.InverseLerp(from, to, v);
- Debug.Log("当f'<0时:" + f);
- v = 40.0f;
- f = Mathf.InverseLerp(from, to, v);
- Debug.Log("当f'>1时:" + f);
- }
- }
InverseLerp
- using UnityEngine;
- using System.Collections;
- public class Lerp_ts : MonoBehaviour {
- float r, g, b;
- void FixedUpdate () {
- r = Mathf.Lerp(0.0f,1.0f,Time.time*0.2f);
- g = Mathf.Lerp(0.0f, 1.0f, -1.0f+Time.time * 0.2f);
- b = Mathf.Lerp(0.0f, 1.0f, -2.0f+Time.time * 0.2f);
- light.color = new Color(r, g, b);
- }
- }
Lerp
- using UnityEngine;
- using System.Collections;
- public class LerpAngle_ts : MonoBehaviour {
- void Start () {
- float a, b;
- a = -50.0f;
- b = 400.0f;
- //a'=360-50=310,b'=-360+400=40,从而可知c=90,
- //从a'沿着逆时针方向可经90度到b',故返回值f=a+c*t=-50+90*0.3=-23
- Debug.Log("test1:"+Mathf.LerpAngle(a,b,0.3f));
- a = 400.0f;
- b = -50.0f;
- //a'=-360+400=40,b'=360-50=310,从而可知c=90,
- //从a'沿着顺时针方向可经90度到b',故返回值f=a-c*t=400-90*0.3=373
- Debug.Log("test2:" + Mathf.LerpAngle(a, b, 0.3f));
- }
- }
LerpAngle
- using UnityEngine;
- using System.Collections;
- public class MoveTowards_ts : MonoBehaviour
- {
- void Start()
- {
- float a, b, d;
- a = 10.0f;
- b = -10.0f;
- d = 5.0f;
- //a>b,且a-d>b,返回值为a-d
- Debug.Log("Test01:" + Mathf.MoveTowards(a, b, d));
- d = 50.0f;
- //a>b,且a-d<b,返回值为b
- Debug.Log("Test02:" + Mathf.MoveTowards(a, b, d));
- a = 10.0f;
- b = 50.0f;
- d = 5.0f;
- //a<b,且a+d<b,返回值为a+d
- Debug.Log("Test03:" + Mathf.MoveTowards(a, b, d));
- d = 50.0f;
- //a<b,且a+d>b,返回值为b
- Debug.Log("Test04:" + Mathf.MoveTowards(a, b, d));
- }
- }
MoveTowards
- using UnityEngine;
- using System.Collections;
- public class MoveTowardsAngle_ts : MonoBehaviour
- {
- float targets = 0.0f;
- float speed = 40.0f;
- void Update()
- {
- //每帧不超过speed * Time.deltaTime度
- float angle = Mathf.MoveTowardsAngle(transform.eulerAngles.y, targets, speed * Time.deltaTime);
- transform.eulerAngles = , angle, );
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "顺时针旋转90度"))
- {
- targets += 90.0f;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "逆时针旋转90度"))
- {
- targets -= 90.0f;
- }
- }
- }
MoveTowardsAngle
- using UnityEngine;
- using System.Collections;
- public class PingPong_ts : MonoBehaviour {
- void Start () {
- float f, t, l;
- t = 11.0f;
- l = 5.0f;
- f = Mathf.PingPong(t,l);
- Debug.Log("l>0,|t|%2l<=l时:"+f);
- t = 17.0f;
- l = 5.0f;
- f = Mathf.PingPong(t, l);
- Debug.Log("l>0,|t|%2l>l时:" + f);
- t = 11.0f;
- l = -5.0f;
- f = Mathf.PingPong(t, l);
- Debug.Log("l<0,|t|%2l<=l时:" + f);
- t = 17.0f;
- l = -5.0f;
- f = Mathf.PingPong(t, l);
- Debug.Log("l<0,|t|%2l>l时:" + f);
- }
- }
PingPong
- using UnityEngine;
- using System.Collections;
- public class Repeat_ts : MonoBehaviour {
- void Start () {
- float f, t, l;
- t = 12.5f;
- l = 5.3f;
- f = Mathf.Repeat(t,l);
- Debug.Log("t>0,l>0时:"+f);
- t = -12.5f;
- l = -5.3f;
- f = Mathf.Repeat(t, l);
- Debug.Log("t<0,l<0时:" + f);
- t = 12.5f;
- l = -5.3f;
- f = Mathf.Repeat(t, l);
- Debug.Log("t>0,l<0时:" + f);
- t = -12.5f;
- l = 5.3f;
- f = Mathf.Repeat(t, l);
- Debug.Log("t<0,l>0时:" + f);
- t = -12.5f;
- l = 0.0f;
- f = Mathf.Repeat(t, l);
- Debug.Log("t<0,l==0时:" + f);
- }
- }
Repeat
- using UnityEngine;
- using System.Collections;
- public class Round_ts : MonoBehaviour
- {
- void Start()
- {
- //设Round(f)中f=a.b
- Debug.Log("b<0.5,f>0:" + Mathf.Round(2.49f));
- Debug.Log("b<0.5,f<0:" + Mathf.Round(-2.49f));
- Debug.Log("b>0.5,f>0:" + Mathf.Round(2.61f));
- Debug.Log("b>0.5,f<0:" + Mathf.Round(-2.61f));
- Debug.Log("b=0.5,a为偶数,f>0:" + Mathf.Round(6.5f));
- Debug.Log("b=0.5,a为偶数,f<0:" + Mathf.Round(-6.5f));
- Debug.Log("b=0.5,a为奇数,f>0:" + Mathf.Round(7.5f));
- Debug.Log("b=0.5,a为奇数,f<0:" + Mathf.Round(-7.5f));
- }
- }
Round
- using UnityEngine;
- using System.Collections;
- public class SmoothDamp_ts : MonoBehaviour
- {
- float targets = 110.0f;//目标值
- float cv1 = 0.0f, cv2 = 0.0f;
- float maxSpeeds = 50.0f;//每帧最大值
- float f1 = 10.0f, f2 = 10.0f;//起始值
- void FixedUpdate()
- {
- //maxSpeed取默认值
- f1 = Mathf.SmoothDamp(f1, targets, ref cv1, 0.5f);
- Debug.Log("f1:" + f1);
- Debug.Log("cv1:" + cv1);
- //maxSpeed取有限值50.0f
- f2 = Mathf.SmoothDamp(f2, targets, ref cv2, 0.5f, maxSpeeds);
- Debug.Log("f2:" + f2);
- Debug.Log("cv2:" + cv2);
- }
- }
SmoothDamp
- using UnityEngine;
- using System.Collections;
- public class SmoothDampAngle_ts : MonoBehaviour
- {
- public Transform targets;
- float smoothTime = 0.3f;
- float distance = 5.0f;
- float yVelocity = 0.0f;
- void Update()
- {
- //返回平滑阻尼角度值
- float yAngle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targets.eulerAngles.y, ref yVelocity, smoothTime);
- Vector3 positions = targets.position;
- //由于使用transform.LookAt,此处计算targets的-z轴方向距离targets为distance,
- //欧拉角为摄像机绕target的y轴旋转yAngle的坐标位置
- positions += Quaternion.Euler(, yAngle, ) * , , -distance);
- //向上偏移2个单位
- transform.position = positions + new Vector3(0.0f, 2.0f, 0.0f);
- transform.LookAt(targets);
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "将targets旋转60度"))
- {
- //更改targets的eulerAngles
- targets.eulerAngles += new Vector3(0.0f, 60.0f, 0.0f);
- }
- }
- }
SmoothDampAngle
- using UnityEngine;
- using System.Collections;
- public class SmoothStep_ts : MonoBehaviour {
- float min = 10.0f;
- float max = 110.0f;
- float f1, f2=0.0f;
- void FixedUpdate () {
- //f1为SmoothStep插值返回值
- f1 = Mathf.SmoothStep(min,max,Time.time);
- //计算相邻两帧插值的变化
- f2 = f1 - f2;
- Debug.Log("f1:"+f1);
- Debug.Log("f2:" + f2);
- f2 = f1;
- }
- }
SmoothStep
6 Matrix4x4类
- using UnityEngine;
- using System.Collections;
- public class MultiplyVector_ts : MonoBehaviour
- {
- public Transform tr;
- Matrix4x4 mv0 = Matrix4x4.identity;
- Matrix4x4 mv1 = Matrix4x4.identity;
- void Start()
- {
- //分别设置变换矩阵mv0和mv1的位置变换和角度变换都不为0
- mv0.SetTRS(Vector3.one * 10.0f, Quaternion.Euler(new Vector3(0.0f, 30.0f, 0.0f)), Vector3.one);
- mv1.SetTRS(Vector3.one * 10.0f, Quaternion.Euler(new Vector3(0.0f, 0.6f, 0.0f)), Vector3.one);
- }
- void Update()
- {
- //用tr来定位变换后的向量
- tr.position = mv1.MultiplyVector(tr.position);
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "方向旋转30度"))
- {
- Vector3 v = mv0.MultiplyVector(new Vector3(10.0f, 0.0f, 0.0f));
- //打印旋转后的向量,其方向发生了旋转
- Debug.Log("变换后向量:"+v);
- //打印旋转后向量的长度,
- //尽管mv0的位置变换不为0,但变换后向量的长度应与变换前相同
- Debug.Log("变换后向量模长:" + v.magnitude);
- }
- }
- }
MultiplyVector
- using UnityEngine;
- using System.Collections;
- public class OrthoAndPerspective_ts : MonoBehaviour
- {
- Matrix4x4 Perspective = Matrix4x4.identity;//透视投影变量
- Matrix4x4 ortho = Matrix4x4.identity;//正交投影变量
- //声明变量,用于记录正交视口的左、右、下、上的值
- float l, r, b, t;
- void Start()
- {
- //设置透视投影矩阵
- Perspective = Matrix4x4.Perspective(65.0f, 1.5f, 0.1f, 500.0f);
- t = 10.0f;
- b = -t;
- //为防止视图变形需要与 Camera.main.aspect相乘
- l = b * Camera.main.aspect;
- r = t * Camera.main.aspect;
- //设置正交投影矩阵
- ortho = Matrix4x4.Ortho(l, r, b, t, 0.1f, 100.0f);
- }
- void OnGUI()
- {
- //使用默认正交投影
- if (GUI.Button(new Rect(10.0f, 8.0f, 150.0f, 20.0f), "Reset Ortho"))
- {
- Camera.main.orthographic = true;
- Camera.main.ResetProjectionMatrix();
- Camera.main.orthographicSize = 5.1f;
- }
- //使用自定义正交投影
- if (GUI.Button(new Rect(10.0f, 38.0f, 150.0f, 20.0f), "use Ortho"))
- {
- ortho = Matrix4x4.Ortho(l, r, b, t, 0.1f, 100.0f);
- Camera.main.orthographic = true;
- Camera.main.ResetProjectionMatrix();
- Camera.main.projectionMatrix = ortho;
- Camera.main.orthographicSize = 5.1f;
- }
- //使用自定义透视投影
- if (GUI.Button(new Rect(10.0f, 68.0f, 150.0f, 20.0f), "use Perspective"))
- {
- Camera.main.orthographic = false;
- Camera.main.projectionMatrix = Perspective;
- }
- //恢复系统默认透视投影
- if (GUI.Button(new Rect(10.0f, 98.0f, 150.0f, 20.0f), "Reset Perspective"))
- {
- Camera.main.orthographic = false;
- Camera.main.ResetProjectionMatrix();
- }
- }
- }
OrthoAndPerspective
- using UnityEngine;
- using System.Collections;
- public class SetTRS_ts : MonoBehaviour
- {
- Vector3 v1 = Vector3.one;
- Vector3 v2 = Vector3.zero;
- void Start()
- {
- Matrix4x4 m1 = Matrix4x4.identity;
- //Position沿Y轴增加5个单位,绕Y轴旋转45度,放缩2倍
- m1.SetTRS(Vector3.up * , Quaternion.Euler(Vector3.up * 45.0f), Vector3.one * 2.0f);
- //也可以使用如下静态方法设置m1变换
- //m1 = Matrix4x4.TRS(Vector3.up * 5, Quaternion.Euler(Vector3.up * 45.0f), Vector3.one * 2.0f);
- v2 = m1.MultiplyPoint3x4(v1);
- Debug.Log("v1的值:" + v1);
- Debug.Log("v2的值:" + v2);
- }
- void FixedUpdate()
- {
- Debug.DrawLine(Vector3.zero, v1, Color.green);
- Debug.DrawLine(Vector3.zero, v2, Color.red);
- }
- }
SetTRS
7 Object类
- using UnityEngine;
- using System.Collections;
- public class Destroy_ts : MonoBehaviour {
- public GameObject GO,Cube;
- void Start () {
- //5秒后销毁GO对象的Rigidbody组件
- Destroy(GO.rigidbody,5.0f);
- //7秒后销毁GO对象中的Destroy_ts脚本
- Destroy(GO.GetComponent<Destroy_ts>(),7.0f);
- //10秒后销毁Cube对象,同时Cube对象的所有组件及子类将一并销毁
- Destroy(Cube, 10.0f);
- }
- }
Destroy
- using UnityEngine;
- using System.Collections;
- public class DontDestoryOnLoad_ts : MonoBehaviour
- {
- public GameObject g1, g2;
- public Renderer re1, re2;
- void Start()
- {
- //g1指向一个顶层父物体对象,在导入新Scene时g1被保存
- DontDestroyOnLoad(g1);
- //g2指向一个子类对象,在导入新Scene时会发现g2没有被保存
- DontDestroyOnLoad(g2);
- //re1指向一个顶层父物体的Renderer组件,在导入新Scene时re1被保存
- DontDestroyOnLoad(re1);
- //re2指向一个子类对象的renderer组件,在导入新Scene时会发现re2指向的对象及组件没有被保存
- DontDestroyOnLoad(re2);
- Application.LoadLevel("FindObjectsOfType_unity");
- }
- }
DontDestoryOnLoad
- using UnityEngine;
- using System.Collections;
- public class FindObjectOfType_ts : MonoBehaviour {
- void Start () {
- GameObject[] gos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
- foreach(GameObject go in gos){
- //1.5秒后销毁除摄像机外的所有GameObject
- if (go.name != "Main Camera")
- {
- Destroy(go, 1.5f);
- }
- }
- Rigidbody[] rbs = FindObjectsOfType(typeof(Rigidbody))as Rigidbody[];
- foreach(Rigidbody rb in rbs){
- //启用除球体外的所有刚体的重力感应
- if(rb.name!="Sphere"){
- rb.useGravity = true;
- }
- }
- }
- }
FindObjectOfType
- using UnityEngine;
- using System.Collections;
- public class GetInstanceID_ts : MonoBehaviour {
- void Start () {
- Debug.Log("gameObject的ID:"+gameObject.GetInstanceID());
- Debug.Log("transform的ID:"+transform.GetInstanceID());
- GameObject g1, g2;
- //从GameObject创建一个对象
- g1=GameObject.CreatePrimitive(PrimitiveType.Cube);
- //克隆对象
- g2=Instantiate(g1,Vector3.zero,Quaternion.identity)as GameObject;
- Debug.Log("GameObject g1的ID:"+g1.GetInstanceID());
- Debug.Log("Transform g1的ID:"+g1.transform.GetInstanceID());
- Debug.Log("GameObject g2的ID:" + g2.GetInstanceID());
- Debug.Log("Transform g2的ID:" + g2.transform.GetInstanceID());
- }
- }
GetInstanceID
- using UnityEngine;
- using System.Collections;
- public class Instantiate_ts : MonoBehaviour {
- public GameObject A;
- public Transform B;
- public Rigidbody C;
- void Start () {
- Object g1 = Instantiate(A,Vector3.zero,Quaternion.identity) as Object;
- Debug.Log("克隆一个Object对象g1:"+g1);
- GameObject g2 = Instantiate(A, Vector3.zero, Quaternion.identity) as GameObject;
- Debug.Log("克隆一个GameObject对象g2:" + g2);
- Transform t1 = Instantiate(B, Vector3.zero, Quaternion.identity) as Transform;
- Debug.Log("克隆一个Transform对象t1:" + t1);
- Rigidbody r1 = Instantiate(C, Vector3.zero, Quaternion.identity) as Rigidbody;
- Debug.Log("克隆一个Rigidbody对象r1:" + r1);
- }
- }
Instantiate
8 Quaternion类
- using UnityEngine;
- using System.Collections;
- public class Angle_ts : MonoBehaviour {
- void Start()
- {
- Quaternion q1 = Quaternion.identity;
- Quaternion q2 = Quaternion.identity;
- q1.eulerAngles = new Vector3(10.0f, 20.0f, 30.0f);
- float f1 = Quaternion.Angle(q1,q2);
- float f2 = 0.0f;
- Vector3 v1 = Vector3.zero;
- q1.ToAngleAxis(out f2, out v1);
- Debug.Log("f1:" + f1);
- Debug.Log("f2:" + f2);
- Debug.Log("q1的欧拉角:" + q1.eulerAngles + " q1的rotation:" + q1);
- Debug.Log("q2的欧拉角:" + q2.eulerAngles + " q2的rotation:" + q2);
- }
- }
Angle
- using UnityEngine;
- using System.Collections;
- public class Dot_ts : MonoBehaviour {
- public Transform A, B;
- Quaternion q1=Quaternion.identity;
- Quaternion q2=Quaternion.identity;
- float f;
- void Start () {
- A.eulerAngles = new Vector3(0.0f,40.0f,0.0f);
- //B比A绕Y轴多转360度
- B.eulerAngles = new Vector3(0.0f, 360.0f+40.0f, 0.0f);
- q1 = A.rotation;
- q2 = B.rotation;
- f = Quaternion.Dot(q1,q2);
- Debug.Log("q1的rotation:"+q1);
- Debug.Log("q2的rotation:" + q2);
- Debug.Log("q1的欧拉角:" + q1.eulerAngles);
- Debug.Log("q2的欧拉角:" + q2.eulerAngles);
- Debug.Log("Dot(q1,q2):"+f);
- }
- }
Dot
- using UnityEngine;
- using System.Collections;
- public class Euler_ts : MonoBehaviour
- {
- //记录欧拉角,单位为角度,可以在Inspector面板中设置
- public float ex, ey, ez;
- //用于记录计算结果
- float qx, qy, qz, qw;
- float PIover180 = 0.0174532925f;//常量
- Quaternion Q = Quaternion.identity;
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 100.0f, 45.0f), "计算"))
- {
- Debug.Log("欧拉角:" + " ex:" + ex + " ey:" + ey + " ez:" + ez);
- //调用方法计算
- Q = Quaternion.Euler(ex, ey, ez);
- Debug.Log("Q.x:" + Q.x + " Q.y:" + Q.y + " Q.z:" + Q.z + " Q.w:" + Q.w);
- //测试算法
- ex = ex * PIover180 / 2.0f;
- ey = ey * PIover180 / 2.0f;
- ez = ez * PIover180 / 2.0f;
- qx = Mathf.Sin(ex) * Mathf.Cos(ey) * Mathf.Cos(ez) + Mathf.Cos(ex) * Mathf.Sin(ey) * Mathf.Sin(ez);
- qy = Mathf.Cos(ex) * Mathf.Sin(ey) * Mathf.Cos(ez) - Mathf.Sin(ex) * Mathf.Cos(ey) * Mathf.Sin(ez);
- qz = Mathf.Cos(ex) * Mathf.Cos(ey) * Mathf.Sin(ez) - Mathf.Sin(ex) * Mathf.Sin(ey) * Mathf.Cos(ez);
- qw = Mathf.Cos(ex) * Mathf.Cos(ey) * Mathf.Cos(ez) + Mathf.Sin(ex) * Mathf.Sin(ey) * Mathf.Sin(ez);
- Debug.Log(" qx:" + qx + " qy:" + qy + " qz:" + qz + " qw:" + qw);
- }
- }
- }
Euler
- using UnityEngine;
- using System.Collections;
- public class EulerAngle_ts : MonoBehaviour
- {
- public Transform A, B;
- Quaternion rotations=Quaternion.identity;
- Vector3 eulerAngle = Vector3.zero;
- float speed = 10.0f;
- void Update()
- {
- //第一种方式:将Quaternion赋值给transform的rotation
- rotations.eulerAngles = new Vector3(0.0f, speed * Time.time, 0.0f);
- A.rotation = rotations;
- //第二种方式:将三维向量代表的欧拉角直接赋值给transform的eulerAngles
- eulerAngle = new Vector3(0.0f, speed * Time.time, 0.0f);
- B.eulerAngles = eulerAngle;
- }
- }
EulerAngle
- using UnityEngine;
- using System.Collections;
- public class FromToRotation_ts : MonoBehaviour
- {
- public Transform A, B, C, D;
- Quaternion q1 = Quaternion.identity;
- void Update()
- {
- //使用实例方法
- //不可直接使用C.rotation.SetFromToRotation(A.position,B.position);
- q1.SetFromToRotation(A.position, B.position);
- C.rotation = q1;
- //使用类方法
- D.rotation = Quaternion.FromToRotation(A.position, B.position);
- //在Scene视图中绘制直线
- Debug.DrawLine(Vector3.zero, A.position, Color.white);
- Debug.DrawLine(Vector3.zero, B.position, Color.white);
- Debug.DrawLine(C.position, C.position + new Vector3(0.0f, 1.0f, 0.0f), Color.white);
- Debug.DrawLine(C.position, C.TransformPoint(Vector3.up * 1.5f), Color.white);
- Debug.DrawLine(D.position, D.position + new Vector3(0.0f, 1.0f, 0.0f), Color.white);
- Debug.DrawLine(D.position, D.TransformPoint(Vector3.up * 1.5f), Color.white);
- }
- }
FromToRotation
- using UnityEngine;
- using System.Collections;
- public class Inverse_ts : MonoBehaviour
- {
- public Transform A, B;
- void Start()
- {
- Quaternion q1 = Quaternion.identity;
- Quaternion q2 = Quaternion.identity;
- q1.eulerAngles = new Vector3(10.0f, 20.0f, 30.0f);
- q2 = Quaternion.Inverse(q1);
- A.rotation = q1;
- B.rotation = q2;
- Debug.Log("q1的欧拉角:" + q1.eulerAngles + " q1的rotation:" + q1);
- Debug.Log("q2的欧拉角:" + q2.eulerAngles + " q2的rotation:" + q2);
- }
- }
Inverse
- using UnityEngine;
- using System.Collections;
- public class LookRotation_ts : MonoBehaviour
- {
- public Transform A, B, C, D;
- Quaternion q1 = Quaternion.identity;
- void Update()
- {
- //使用实例方法
- //不可直接使用C.rotation.SetLookRotation(A.position,B.position);
- q1.SetLookRotation(A.position, B.position);
- C.rotation = q1;
- //使用类方法
- D.rotation = Quaternion.LookRotation(A.position, B.position);
- //绘制直线,请在Scene视图中查看
- Debug.DrawLine(Vector3.zero, A.position, Color.white);
- Debug.DrawLine(Vector3.zero, B.position, Color.white);
- Debug.DrawLine(C.position, C.TransformPoint(Vector3.up * 2.5f), Color.white);
- Debug.DrawLine(C.position, C.TransformPoint(Vector3.forward * 2.5f), Color.white);
- Debug.DrawLine(D.position, D.TransformPoint(Vector3.up * 2.5f), Color.white);
- Debug.DrawLine(D.position, D.TransformPoint(Vector3.forward * 2.5f), Color.white);
- }
- }
LookRotation
- using UnityEngine;
- using System.Collections;
- public class QxQ_ts : MonoBehaviour {
- public Transform A, B;
- void Start () {
- //设置A的欧拉角
- //试着更改各个分量查看B的不同旋转状态
- A.eulerAngles = new Vector3(1.0f,1.5f,2.0f);
- }
- void Update () {
- B.rotation *= A.rotation;
- //输出B的欧拉角,注意观察B的欧拉角变化
- Debug.Log(B.eulerAngles);
- }
- }
QxQ
- using UnityEngine;
- using System.Collections;
- public class QxV_ts : MonoBehaviour
- {
- public Transform A;
- float speed = 0.1f;
- //初始化A的position和eulerAngles
- void Start()
- {
- A.position = Vector3.zero;
- A.eulerAngles = new Vector3(0.0f, 45.0f, 0.0f);
- }
- void Update()
- {
- //沿着A的自身坐标系的forward方向每帧前进speed距离
- A.position += A.rotation * (Vector3.forward * speed);
- Debug.Log(A.position);
- }
- }
QxV
- using UnityEngine;
- using System.Collections;
- public class RotateTowards_ts : MonoBehaviour {
- public Transform A, B, C;
- float speed = 10.0f;
- void Update()
- {
- C.rotation = Quaternion.RotateTowards(A.rotation, B.rotation, Time.time * speed-40.0f);
- Debug.Log("C与A的欧拉角的差值:" + (C.eulerAngles-A.eulerAngles) + " maxDegreesDelta:" + (Time.time * speed - 40.0f));
- }
- }
RotateTowards
- using UnityEngine;
- using System.Collections;
- public class SetFromToRotation_ts : MonoBehaviour {
- public Transform A, B, C;
- Quaternion q1 = Quaternion.identity;
- void Update () {
- //不可直接使用C.rotation.SetFromToRotation(A.position,B.position);
- q1.SetFromToRotation(A.position,B.position);
- C.rotation = q1;
- Debug.DrawLine(Vector3.zero,A.position,Color.red);
- Debug.DrawLine(Vector3.zero, B.position, Color.green);
- Debug.DrawLine(C.position, C.position+new Vector3(0.0f,1.0f,0.0f), Color.black);
- Debug.DrawLine(C.position, C.TransformPoint(Vector3.up*1.5f), Color.yellow);
- }
- }
SetFromToRotation
- using UnityEngine;
- using System.Collections;
- public class SetLookRotation_ts : MonoBehaviour
- {
- public Transform A, B, C;
- Quaternion q1 = Quaternion.identity;
- void Update()
- {
- //不可直接使用C.rotation.SetLookRotation(A.position,B.position);
- q1.SetLookRotation(A.position, B.position);
- C.rotation = q1;
- //分别绘制A、B和C.right的朝向线
- //请在Scene视图中查看
- Debug.DrawLine(Vector3.zero, A.position, Color.red);
- Debug.DrawLine(Vector3.zero, B.position, Color.green);
- Debug.DrawLine(C.position, C.TransformPoint(Vector3.right * 2.5f), Color.yellow);
- Debug.DrawLine(C.position, C.TransformPoint(Vector3.forward * 2.5f), Color.black);
- //分别打印C.right与A、B的夹角
- Debug.Log("C.right与A的夹角:" + Vector3.Angle(C.right, A.position));
- Debug.Log("C.right与B的夹角:" + Vector3.Angle(C.right, B.position));
- //C.up与B的夹角
- Debug.Log("C.up与B的夹角:" + Vector3.Angle(C.up, B.position));
- }
- }
SetLookRotation
- using UnityEngine;
- using System.Collections;
- public class Slerp_ts : MonoBehaviour
- {
- public Transform A, B, C, D;
- float speed = 0.2f;
- //分别演示方法Slerp和Lerp的使用
- void Update()
- {
- C.rotation = Quaternion.Slerp(A.rotation, B.rotation, Time.time * speed);
- D.rotation = Quaternion.Lerp(A.rotation, B.rotation, Time.time * speed);
- }
- }
Slerp
- using UnityEngine;
- using System.Collections;
- public class ToAngleAxis_ts : MonoBehaviour
- {
- public Transform A, B;
- float angle;
- Vector3 axis = Vector3.zero;
- void Update()
- {
- //使用ToAngleAxis获取A的Rotation的旋转轴和角度
- A.rotation.ToAngleAxis(out angle, out axis);
- //使用AngleAxis设置B的rotation,使得B的rotation状态的和A相同
- //可以在程序运行时修改A的rotation查看B的状态
- B.rotation = Quaternion.AngleAxis(angle, axis);
- }
- }
ToAngleAxis
9 Random类
- using UnityEngine;
- using System.Collections;
- public class insideUnitCircle_ts : MonoBehaviour
- {
- public GameObject go;
- void Start()
- {
- //每隔0.4秒执行一次use_rotationUniform方法
- InvokeRepeating("use_rotationUniform", 1.0f, 0.4f);
- }
- void use_rotationUniform()
- {
- //在半径为5的圆内随机位置实例化一个GameObject对象
- //Vector2实例转为Vector3时,z轴分量默认为0
- Instantiate(go, Random.insideUnitCircle * 5.0f, Quaternion.identity);
- //在半径为5的球内随机位置实例化一个GameObject对象
- Instantiate(go, Vector3.forward * 15.0f + 5.0f * Random.insideUnitSphere, Quaternion.identity);
- //在半径为5的球表面随机位置实例化一个GameObject对象
- Instantiate(go, Vector3.forward * 30.0f + 5.0f * Random.onUnitSphere, Quaternion.identity);
- }
- }
insideUnitCircle
- using UnityEngine;
- using System.Collections;
- public class rotationUniform_ts : MonoBehaviour
- {
- public GameObject go;
- GameObject cb, sp;
- GameObject cb1, sp1;
- void Start()
- {
- //分别获取cb、sp、cb1和sp1对象
- cb = GameObject.Find("Cube");
- sp = GameObject.Find("Cube/Sphere");
- cb1 = GameObject.Find("Cube1");
- sp1 = GameObject.Find("Cube1/Sphere1");
- //每隔0.4秒执行一次use_rotationUniform方法
- InvokeRepeating("use_rotationUniform", 1.0f, 0.4f);
- }
- void use_rotationUniform()
- {
- //使用rotationUniform产生符合均匀分布特征的rotation
- cb.transform.rotation = Random.rotationUniform;
- //使用rotation产生一个随机rotation
- cb1.transform.rotation = Random.rotation;
- //分别在sp和sp1的位置实例化一个GameObject对象
- Instantiate(go, sp.transform.position, Quaternion.identity);
- Instantiate(go, sp1.transform.position, Quaternion.identity);
- }
- }
rotationUniform
- using UnityEngine;
- using System.Collections;
- public class Seed_ts : MonoBehaviour
- {
- void Start()
- {
- //设置随机数的种子
- //不同的种子产生不同的随机数序列
- //对于相同的种子,在程序每次启动时其序列是相同的
- Random.seed = ;
- }
- void Update()
- {
- Debug.Log(Random.value);
- }
- }
Seed
10 Rigidbody类
- using UnityEngine;
- using System.Collections;
- public class AddExplosionForce_ts : MonoBehaviour
- {
- public Rigidbody A;
- public Transform Z;//Scene视图中显示爆炸点坐标
- Vector3 E = Vector3.zero;//爆炸点坐标
- float F, R, y_m;
- bool is_change = false;
- void Start()
- {
- //初始位置使得爆炸点和A的X、Y轴坐标值相等
- //可以更改F及R的大小查看运行时效果
- E = A.position - new Vector3(0.0f, 0.0f, 3.0f);
- F = 40.0f;
- R = 10.0f;
- y_m = 0.0f;
- A.transform.localScale = Vector3.one * 2.0f;
- Z.position = E;
- }
- void FixedUpdate()
- {
- if (is_change)
- {
- A.AddExplosionForce(F, E, R, y_m);
- is_change = false;
- }
- }
- void OnGUI()
- {
- //当爆炸点和A的重心的两个坐标轴的值相等时,A将平移不旋转
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "刚体移动不旋转"))
- {
- is_change = true;
- inits();
- }
- //虽然受力大小不变,但产生扭矩发生旋转
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "刚体发生移动但受力大小不变"))
- {
- inits();
- A.position += new Vector3(0.5f, -0.5f, 0.0f);
- is_change = true;
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "按最近表面距离计算力的大小"))
- {
- inits();
- A.position += new Vector3(0.0f, 2.0f, 0.0f);
- is_change = true;
- }
- //Y轴的偏移改变了A的原始方向
- //可以更改y_m的值查看不同的效果
- if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "Y轴发生偏移"))
- {
- inits();
- is_change = true;
- A.position += new Vector3(0.0f, 2.0f, 0.0f);
- y_m = -2.0f;
- }
- }
- //初始化数据
- void inits()
- {
- A.velocity = Vector3.zero;
- A.angularVelocity = Vector3.zero;
- A.position = E + new Vector3(0.0f, 0.0f, 3.0f);
- A.transform.rotation = Quaternion.identity;
- y_m = 0.0f;
- }
- }
AddExplosionForce
- using UnityEngine;
- using System.Collections;
- public class AddForceAtPosition_ts : MonoBehaviour
- {
- public Rigidbody A, B, C;
- Vector3 m_force = new Vector3(0.0f, 0.0f, 10.0f);
- void FixedUpdate()
- {
- //当力的作用点在刚体重心时,刚体不发生旋转
- A.AddForceAtPosition(m_force, A.transform.position, ForceMode.Force);
- //当力的作用点不在刚体重心时,由于作用点的扭矩使得刚体发生旋转
- B.AddForceAtPosition(m_force, B.transform.position + new Vector3(0.0f, 0.3f, 0.0f), ForceMode.Force);
- //但是,当力的作用点与刚体重心坐标的差值向量与作用力的方向同向时不发生旋转
- C.AddForceAtPosition(m_force, C.transform.position + new Vector3(0.0f, 0.0f, 0.3f), ForceMode.Force);
- Debug.Log("A的欧拉角:" + A.transform.eulerAngles);
- Debug.Log("B的欧拉角:" + B.transform.eulerAngles);
- Debug.Log("C的欧拉角:" + C.transform.eulerAngles);
- }
- }
AddForceAtPosition
- using UnityEngine;
- using System.Collections;
- public class AddTorque_ts : MonoBehaviour {
- public Rigidbody R;
- Vector3 m_torque = new Vector3(0.0f,10.0f,0.0f);
- void Start () {
- R.transform.localScale = new Vector3(2.0f,2.0f,2.0f);
- R.mass = 1.0f;
- R.angularDrag = 0.0f;
- Debug.Log("刚体默认的最大角速度:"+R.maxAngularVelocity);
- //可以使用如下代码更改刚体的最大角速度
- //R.maxAngularVelocity = 10.0f;
- }
- void FixedUpdate () {
- //每帧给物体添加一个扭矩,使其转速不断加快
- R.AddTorque(m_torque,ForceMode.Force);
- Debug.Log("刚体当前角速度:"+R.angularVelocity);
- }
- }
AddTorque
- using UnityEngine;
- using System.Collections;
- public class ATorC_ts : MonoBehaviour
- {
- //开始接触
- void OnTriggerEnter(Collider other)
- {
- Debug.Log("A物体的OnTriggerEnter被调用,被接触的物体为" + other.name);
- }
- //结束接触
- void OnTriggerExit(Collider other)
- {
- Debug.Log("A物体的OnTriggerExit被调用,被接触的物体为" + other.name);
- }
- //保持接触
- void OnTriggerStay(Collider other)
- {
- Debug.Log("A物体的OnTriggerStay被调用,被接触的物体为" + other.name);
- }
- //开始碰撞
- void OnCollisionEnter(Collision collision)
- {
- Debug.Log("A物体的OnCollisionEnter被调用,被碰撞的物体为" + collision.gameObject.name);
- }
- //退出碰撞
- void OnCollisionExit(Collision collision)
- {
- Debug.Log("A物体的OnCollisionExit被调用,被碰撞的物体为" + collision.gameObject.name);
- }
- //保持碰撞
- void OnCollisionStay(Collision collision)
- {
- Debug.Log("A物体的OnCollisionStay被调用,被碰撞的物体为" + collision.gameObject.name);
- }
- }
ATorC
- using UnityEngine;
- using System.Collections;
- public class BTorC_ts : MonoBehaviour
- {
- void OnTriggerEnter(Collider other)
- {
- Debug.Log("B物体的OnTriggerEnter被调用,被接触的物体为" + other.name);
- }
- void OnTriggerExit(Collider other)
- {
- Debug.Log("B物体的OnTriggerExit被调用,被接触的物体为" + other.name);
- }
- void OnTriggerStay(Collider other)
- {
- Debug.Log("B物体的OnTriggerStay被调用,被接触的物体为" + other.name);
- }
- void OnCollisionEnter(Collision collision)
- {
- Debug.Log("B物体的OnCollisionEnter被调用,被碰撞的物体为" + collision.gameObject.name);
- }
- void OnCollisionExit(Collision collision)
- {
- Debug.Log("B物体的OnCollisionExit被调用,被碰撞的物体为" + collision.gameObject.name);
- }
- void OnCollisionStay(Collision collision)
- {
- Debug.Log("B物体的OnCollisionStay被调用,被碰撞的物体为" + collision.gameObject.name);
- }
- }
BTorC
- using UnityEngine;
- using System.Collections;
- public class ClosestPointOnBounds_ts : MonoBehaviour
- {
- public Rigidbody r;
- void Start()
- {
- r.position = new Vector3(0.0f,4.0f,0.0f);
- Debug.Log(r.ClosestPointOnBounds(new Vector3(5.0f, 4.0f, 0.0f)));
- }
- }
ClosestPointOnBounds
- using UnityEngine;
- using System.Collections;
- public class CollisionDetectionMode_ts : MonoBehaviour
- {
- public Rigidbody A, B;
- Vector3 v1, v2;
- void Start()
- {
- A.useGravity = false;
- B.useGravity = false;
- v1 = A.position;
- v2 = B.position;
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Discrete模式不被穿越"))
- {
- inists();
- A.collisionDetectionMode = CollisionDetectionMode.Discrete;
- B.collisionDetectionMode = CollisionDetectionMode.Discrete;
- A.velocity = new Vector3(0.0f,-10.0f,0.0f);
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Discrete模式被穿越"))
- {
- inists();
- A.collisionDetectionMode = CollisionDetectionMode.Discrete;
- B.collisionDetectionMode = CollisionDetectionMode.Discrete;
- A.velocity = new Vector3(0.0f, -40.0f, 0.0f);
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "Continuous模式不被穿越"))
- {
- inists();
- A.collisionDetectionMode = CollisionDetectionMode.Continuous;
- B.collisionDetectionMode = CollisionDetectionMode.Continuous;
- A.velocity = new Vector3(0.0f, -20.0f, 0.0f);
- }
- if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "Continuous模式被穿越"))
- {
- inists();
- A.collisionDetectionMode = CollisionDetectionMode.Continuous;
- B.collisionDetectionMode = CollisionDetectionMode.Continuous;
- A.velocity = new Vector3(0.0f, -15.0f, 0.0f);
- B.velocity = new Vector3(0.0f, 15.0f, 0.0f);
- }
- if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "ContinuousDynamic模式"))
- {
- inists();
- A.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
- B.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic;
- A.velocity = new Vector3(0.0f, -200.0f, 0.0f);
- B.velocity = new Vector3(0.0f, 200.0f, 0.0f);
- }
- if (GUI.Button(new Rect(10.0f, 260.0f, 200.0f, 45.0f), "重置"))
- {
- inists();
- }
- }
- //初始化A、B
- void inists() {
- A.position = v1;
- A.rotation = Quaternion.identity;
- A.velocity = Vector3.zero;
- A.angularVelocity = Vector3.zero;
- B.position = v2;
- B.rotation = Quaternion.identity;
- B.velocity = Vector3.zero;
- B.angularVelocity = Vector3.zero;
- }
- }
CollisionDetectionMode
- using UnityEngine;
- using System.Collections;
- public class Drag_ts : MonoBehaviour
- {
- public Rigidbody R;
- float drags = 20.0f;
- ";
- //初始化R.drag
- void Start()
- {
- R.drag = drags;
- }
- void OnGUI()
- {
- GUI.Label(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Gravity:" + Physics.gravity);
- str = (GUI.TextField(new Rect(10.0f, 60.0f, 200.0f, 45.0f), str));
- if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "compute"))
- {
- drags = float.Parse(str);
- R.drag = drags;
- }
- GUI.Label(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "Velocity:" + R.velocity.y);
- GUI.Label(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "drag:" + drags);
- }
- }
Drag
- using UnityEngine;
- using System.Collections;
- public class ForceMode_ts : MonoBehaviour
- {
- public Rigidbody A, B, C, D;
- //作用力向量
- Vector3 forces = new Vector3(10.0f, 0.0f, 0.0f);
- void Start()
- {
- //初始化四个刚体的质量,使其相同
- A.mass = 2.0f;
- B.mass = 2.0f;
- C.mass = 2.0f;
- D.mass = 2.0f;
- //对A、B、C、D采用不同的作用力方式
- //注意此处只是对物体增加了1帧的作用力
- //如果要对刚体产生持续作用力请把以下代码放在FixedUpdate()方法中
- A.AddForce(forces, ForceMode.Force);
- B.AddForce(forces, ForceMode.Acceleration);
- C.AddForce(forces, ForceMode.Impulse);
- D.AddForce(forces, ForceMode.VelocityChange);
- }
- void FixedUpdate()
- {
- Debug.Log("ForceMode.Force作用方式下A每帧增加的速度:" + A.velocity);
- Debug.Log("ForceMode.Acceleration作用方式下B每帧增加的速度:" + B.velocity);
- Debug.Log("ForceMode.Impulse作用方式下C每帧增加的速度:" + C.velocity);
- Debug.Log("ForceMode.VelocityChange作用方式下D每帧增加的速度:" + D.velocity);
- }
- }
ForceMode
- using UnityEngine;
- using System.Collections;
- public class GetRelativePointVelocity_ts : MonoBehaviour
- {
- public Rigidbody A;
- string str = "";
- void Start()
- {
- //给A施加一帧的力,使其产生速度
- A.AddForce(Vector3.forward * 100.0f);
- }
- void FixedUpdate()
- {
- //A.transform.TransformPoint(Vector3.forward):获取A的局部坐标系中Vector3.forward点在世界坐标系中的坐标值
- //这样A.GetPointVelocity(A.transform.TransformPoint(Vector3.forward))和
- //A.GetRelativePointVelocity(Vector3.forward)返回的是同一点的速度,即它们的返回值应该相等。
- Debug.Log(str + "GetPointVelocity: " + A.GetPointVelocity(A.transform.TransformPoint(Vector3.forward)));
- Debug.Log(str + "GetRelativePointVelocity: " + A.GetRelativePointVelocity(Vector3.forward));
- }
- void OnGUI()
- {
- //当刚体角速度为Vector3.zero时,任何点的速度都和刚体速度相等
- //当刚体角速度不为Vector3.zero时,坐标系中各个点的速度是不等的
- //GetPointVelocity和GetRelativePointVelocity只是两种计算坐标点的不同方法
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "增加角速度"))
- {
- A.angularVelocity = new Vector3(0.0f, 45.0f, 0.0f);
- str = "增加角速度后,";
- }
- }
- }
GetRelativePointVelocity
- using UnityEngine;
- using System.Collections;
- public class GraAndKin_ts : MonoBehaviour
- {
- public Rigidbody A, B;
- string str_AG = "";
- string str_AK = "";
- string str_BK = "";
- Vector3 v1, v2;
- void Start()
- {
- //为了更好的演示,将重力加速度降低
- Physics.gravity = new Vector3(0.0f,-0.5f,0.0f);
- A.useGravity = false;
- B.useGravity = false;
- A.isKinematic = false;
- B.isKinematic = false;
- str_AG = "A开启重力感应";
- str_AK = "A关闭物理感应";
- str_BK = "B关闭物理感应";
- v1 = A.position;
- v2 = B.position;
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), str_AG))
- {
- if (A.useGravity)
- {
- A.useGravity = false;
- str_AG = "A开启重力感应";
- }
- else
- {
- A.useGravity = true;
- str_AG = "A关闭重力感应";
- }
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), str_AK))
- {
- if (A.isKinematic)
- {
- A.isKinematic = false;
- str_AK = "A关闭物理感应";
- }
- else
- {
- A.isKinematic = true;
- str_AK = "A开启物理感应";
- }
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), str_BK))
- {
- if (B.isKinematic)
- {
- B.isKinematic = false;
- str_BK = "B关闭物理感应";
- }
- else
- {
- B.isKinematic = true;
- str_BK = "B开启物理感应";
- }
- }
- if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "重置"))
- {
- A.position = v1;
- A.rotation = Quaternion.identity;
- B.position = v2;
- B.rotation = Quaternion.identity;
- }
- }
- }
GraAndKin
- using UnityEngine;
- using System.Collections;
- public class inertiaTensor_ts : MonoBehaviour
- {
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 160.0f, 45.0f), "X轴惯性张量大于Y轴"))
- {
- transform.position = , , );
- //transform绕Z轴旋转45度
- transform.rotation = Quaternion.Euler(0.0f, 0.0f, 45.0f);
- //设置rigidbody的惯性张量
- //X轴分量值大于Y轴,则刚体会向X轴方向倾斜
- rigidbody.inertiaTensor = new Vector3(15.0f, 10.0f, 1.0f);
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 160.0f, 45.0f), "Y轴惯性张量大于X轴"))
- {
- transform.position = , , );
- transform.rotation = Quaternion.Euler(0.0f, 0.0f, 45.0f);
- //设置rigidbody的惯性张量
- //X轴分量值小于Y轴,则刚体会向Y轴方向倾斜
- rigidbody.inertiaTensor = new Vector3(5.0f, 10.0f, 1.0f);
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 160.0f, 45.0f), "X轴和Y轴惯性张量相同"))
- {
- transform.position = , , );
- transform.rotation = Quaternion.Euler(0.0f, 0.0f, 45.0f);
- //设置rigidbody的惯性张量
- //X轴和Y轴惯性张量相同,则刚体会保持静止
- rigidbody.inertiaTensor = new Vector3(10.0f, 10.0f, 1.0f);
- }
- }
- }
inertiaTensor
- using UnityEngine;
- using System.Collections;
- public class Mass_ts : MonoBehaviour
- {
- public Rigidbody r1, r2, r3, r4, r5;
- Vector3 v3 = Vector3.zero;
- void Start()
- {
- //r1和r2质量不同,但它们的速度始终相同
- //r4和r5质量不同,当r3以同样的速度撞r4和r5后速度明显不同
- r1.mass = 0.1f;
- r2.mass = 5.0f;
- r3.mass = 2.0f;
- r4.mass = 0.1f;
- r5.mass = 4.0f;
- r3.useGravity = false;
- r4.useGravity = false;
- r5.useGravity = false;
- v3 = r3.position;
- }
- void FixedUpdate()
- {
- Debug.Log(Time.time + " R1的速度:" + r1.velocity);
- Debug.Log(Time.time + " R2的速度:" + r2.velocity);
- Debug.Log(Time.time + " R3的速度:" + r3.velocity);
- Debug.Log(Time.time + " R4的速度:" + r4.velocity);
- Debug.Log(Time.time + " R5的速度:" + r5.velocity);
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "用R3撞R4"))
- {
- r3.position = v3;
- r3.rotation = Quaternion.identity;
- r3.velocity = new Vector3(4.0f, 0.0f, 0.0f);
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "用R3撞R5"))
- {
- r3.position = v3;
- r3.rotation = Quaternion.identity;
- r3.velocity = new Vector3(0.0f, 0.0f, 4.0f);
- }
- }
- }
Mass
- using UnityEngine;
- using System.Collections;
- public class Mds_ts : MonoBehaviour
- {
- public Rigidbody A, B;
- public static bool is_AC = false, is_BC = false;
- public static Vector3 A_v = Vector3.zero, B_v = Vector3.zero;
- void Start()
- {
- //如果不使用SetDensity则scale的大小对刚体质量无影响
- Debug.Log("A的质量mass:" + A.mass);
- A.transform.localScale = A.transform.localScale * 2.0f;
- Debug.Log("scale值放大后A的质量mass:" + A.mass);
- A.transform.localScale = A.transform.localScale / 2.0f;
- //注意,如果要使用SetDensity请先设定scale值再设置Density
- //否则一旦density确定质量也就确定了,再去设置scale将对质量改变不起作用
- A.transform.localScale = A.transform.localScale * 2.0f;
- A.SetDensity(2.0f);
- Debug.Log("改变density和scale值后A的质量mass:" + A.mass);
- //给A一个初始速度
- A.velocity = new Vector3(0.0f, 0.0f, 10.0f);
- 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)));
- }
- void FixedUpdate()
- {
- if (is_AC && is_BC)
- {
- 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)));
- }
- }
- }
Mds
- using UnityEngine;
- using System.Collections;
- public class MdsA_ts : MonoBehaviour {
- void OnCollisionExit(Collision collisionInfo)
- {
- Mds_ts.A_v = rigidbody.velocity;
- Mds_ts.is_AC = true;
- }
- }
MdsA
- using UnityEngine;
- using System.Collections;
- public class MdsB_ts : MonoBehaviour {
- void OnCollisionExit(Collision collisionInfo)
- {
- Mds_ts.B_v = rigidbody.velocity;
- Mds_ts.is_BC = true;
- }
- }
MdsB
- using UnityEngine;
- using System.Collections;
- public class MovePOrR_ts : MonoBehaviour
- {
- public Rigidbody A;
- bool is_pr = false;
- void Start()
- {
- A.velocity = Vector3.forward * 20.0f;
- A.angularVelocity = Vector3.up * 90.0f;
- //当isKinematic == true时刚体的动力学模拟将失效
- //此时可以使用MovePosition和MoveRotation对刚体进行移动和旋转
- A.isKinematic = true;
- }
- void FixedUpdate()
- {
- if (is_pr)
- {
- A.MovePosition(A.position + Vector3.forward * Time.deltaTime);
- Quaternion deltaRotation = Quaternion.Euler(Vector3.up * 90.0f * Time.deltaTime);
- A.MoveRotation(A.rotation * deltaRotation);
- }
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "刚体移动与旋转"))
- {
- is_pr = true;
- }
- }
- }
MovePOrR
- using UnityEngine;
- using System.Collections;
- public class SleepOrWake_ts : MonoBehaviour
- {
- public Rigidbody A;
- void Awake()
- {
- A.Sleep();
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Sleep"))
- {
- if (!A.IsSleeping())
- {
- A.Sleep();
- }
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "WakeUp"))
- {
- if (A.IsSleeping())
- {
- A.WakeUp();
- }
- }
- Debug.Log("A物体的Y坐标:" + A.transform.position.y+" A物体是否处于休眠状态:"+A.IsSleeping());
- }
- }
SleepOrWake
- using UnityEngine;
- using System.Collections;
- public class SweepTest_ts : MonoBehaviour
- {
- public GameObject A, B;
- RaycastHit hit;
- float len = 10.0f;//有效探测距离
- void Start()
- {
- A.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
- B.transform.position = new Vector3(4.0f, 1.0f, 1.0f);
- }
- void FixedUpdate()
- {
- //探测刚体A的right方向(即右侧)len距离内是否存在物体
- if (A.rigidbody.SweepTest(A.transform.right, out hit, len))
- {
- Debug.Log("A物体右侧存在物体:" + hit.transform.name + " 其距离A的距离为:" + hit.distance);
- }
- else
- {
- Debug.Log("A物体右侧" + len + "米范围内没检测到带碰撞器的物体!");
- }
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "设置B坐标使A无法探测到"))
- {
- //重置B的position,使得物体A、B的间距大于len值
- B.transform.position = new Vector3(12.0f, 1.0f, 1.0f);
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "取消B中的Rigidbody组件"))
- {
- //销毁B物体中的Rigidbody组件
- //运行程序可以发现,B物体中是否存在Rigidbody对探测结果没有影响
- if (B.GetComponent<Rigidbody>())
- {
- Destroy(B.GetComponent<Rigidbody>());
- }
- }
- if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "取消B中的Collider组件"))
- {
- //销毁B物体中的Collider组件
- //运行程序可以发现,如果B中无Collider组件则A无论如何也探测不到B的存在
- if (B.GetComponent<Collider>())
- {
- Destroy(B.GetComponent<Collider>());
- }
- }
- //对B物体的状态重置
- if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "重置"))
- {
- B.transform.position = new Vector3(4.0f, 1.0f, 1.0f);
- if (!B.GetComponent<Collider>())
- {
- B.AddComponent<BoxCollider>();
- }
- if (!B.GetComponent<Rigidbody>())
- {
- B.AddComponent<Rigidbody>();
- B.rigidbody.useGravity = false;
- }
- }
- }
- }
SweepTest
- using UnityEngine;
- using System.Collections;
- public class SweepTestAll_ts : MonoBehaviour
- {
- public GameObject A, B, C, D;
- RaycastHit[] hits;
- float len = 10.0f;//有效探测距离
- void Start()
- {
- A.transform.position = new Vector3(1.0f, 1.0f, 1.0f);
- B.transform.position = new Vector3(4.0f, 1.0f, 1.0f);
- C.transform.position = new Vector3(7.0f, 1.0f, 1.0f);
- //D物体超出了A的有效探测距离,不会被探测到
- D.transform.position = new Vector3(12.0f, 1.0f, 1.0f);
- hits = A.rigidbody.SweepTestAll(A.transform.right, len);
- float l = hits.Length;
- Debug.Log("A探测到的物体个数为:" + l + " 它们分别是:");
- //遍历探测结果
- foreach (RaycastHit hit in hits)
- {
- Debug.Log(hit.transform.name);
- }
- }
- }
SweepTestAll
- using UnityEngine;
- using System.Collections;
- public class TriggerOrCollision_ts : MonoBehaviour
- {
- public GameObject A, B;
- Vector3 p_a, p_b;
- ;
- //将物体A、B的初始位置赋给p_a和p_b,用于重置物体组件时使用
- void Start()
- {
- p_a = A.transform.position;
- p_b = B.transform.position;
- }
- //控制物体A的移动
- void FixedUpdate()
- {
- )
- {
- A.transform.Translate(Vector3.forward * Time.deltaTime);
- }
- }
- void OnGUI()
- {
- //当A物体无Rigidbody组件时,
- //无论B是否有Rigidbody都不会激活A和B物体的脚本中的OnCollisionXXX或OnTriggerXXX方法
- if (GUI.Button(new Rect(10.0f, 10.0f, 280.0f, 45.0f), "A物体无Rigidbody组件"))
- {
- inists();
- which_change = ;
- if (A.GetComponent<Rigidbody>())
- {
- Destroy(A.GetComponent<Rigidbody>());
- }
- }
- //当A物体有Rigidbody组件时,
- //一定会激活A和B物体的脚本中的OnCollisionXXX或OnTriggerXXX方法
- if (GUI.Button(new Rect(10.0f, 60.0f, 280.0f, 45.0f), "A有Rigidbody组件,B无Rigidbody组件"))
- {
- inists();
- which_change = ;
- if (!A.GetComponent<Rigidbody>())
- {
- A.AddComponent<Rigidbody>();
- A.rigidbody.useGravity = false;
- }
- if (B.GetComponent<Rigidbody>())
- {
- Destroy(B.GetComponent<Rigidbody>());
- }
- A.rigidbody.velocity = Vector3.forward;
- }
- //当A物体有Rigidbody组件时,
- //且A与B物体IsTrigger都未选中时,只会激活A和B物体的脚本中的OnCollisionXXX方法
- if (GUI.Button(new Rect(10.0f, 110.0f, 280.0f, 45.0f), "A与B物体IsTrigger都未选中"))
- {
- inists();
- which_change = ;
- A.GetComponent<Collider>().isTrigger = false;
- B.GetComponent<Collider>().isTrigger = false;
- if (!A.GetComponent<Rigidbody>())
- {
- A.AddComponent<Rigidbody>();
- A.rigidbody.useGravity = false;
- }
- A.rigidbody.velocity = Vector3.forward;
- }
- //当A物体有Rigidbody组件时,
- //且A与B物体IsTrigger至少有一个被选中时,只会激活A和B物体的脚本中的OnTriggerXXX方法
- if (GUI.Button(new Rect(10.0f, 160.0f, 280.0f, 45.0f), "A物体IsTrigger被选中"))
- {
- inists();
- which_change = ;
- A.GetComponent<Collider>().isTrigger = true;
- if (!A.GetComponent<Rigidbody>())
- {
- A.AddComponent<Rigidbody>();
- A.rigidbody.useGravity = false;
- }
- A.rigidbody.velocity = Vector3.forward;
- }
- if (GUI.Button(new Rect(10.0f, 210.0f, 280.0f, 45.0f), "重置"))
- {
- inists();
- which_change = ;
- }
- }
- //初始化数据
- void inists()
- {
- if (A.GetComponent<Rigidbody>())
- {
- A.rigidbody.velocity = Vector3.zero;
- A.rigidbody.angularVelocity = Vector3.zero;
- }
- if (B.GetComponent<Rigidbody>())
- {
- B.rigidbody.velocity = Vector3.zero;
- B.rigidbody.angularVelocity = Vector3.zero;
- }
- A.transform.position = p_a;
- A.transform.rotation = Quaternion.identity;
- B.transform.position = p_b;
- B.transform.rotation = Quaternion.identity;
- }
- }
TriggerOrCollision
- using UnityEngine;
- using System.Collections;
- public class Velocity_ts : MonoBehaviour {
- public Rigidbody r1,r2;
- // Use this for initialization
- void Start () {
- //给父物体r1一个向-z轴的速度,给子物体一个+z轴的速度
- r1.velocity = new Vector3(0.0f,0.0f,-15.0f);
- r2.velocity = new Vector3(0.0f, 0.0f, 10.0f);
- }
- void OnGUI() {
- GUI.Label(new Rect(10.0f,8.0f,300.0f,40.0f),"R1当前速度:"+r1.velocity);
- GUI.Label(new Rect(10.0f,58.0f,300.0f,40.0f),"R2当前速度:"+r2.velocity);
- Debug.Log("R1当前速度:" + r1.velocity);
- Debug.Log("R2当前速度:" + r2.velocity);
- }
- }
Velocity
11 Time类
- using UnityEngine;
- using System.Collections;
- public class newScene01_ts : MonoBehaviour
- {
- float t1 = 0.0f;
- void Update()
- {
- t1 = Time.deltaTime;
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "返回原来场景"))
- {
- Application.LoadLevel("Time_unity");
- }
- GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前游戏场景名字:" + Application.loadedLevelName);
- GUI.Label(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "当前游戏已运行时间Time.time:" + Time.time);
- GUI.Label(new Rect(10.0f, 160.0f, 400.0f, 45.0f), "当前场景已运行时间Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);
- GUI.Label(new Rect(10.0f, 210.0f, 300.0f, 45.0f), "上一帧消耗的时间Time.deltaTime:" + t1);
- GUI.Label(new Rect(10.0f, 260.0f, 300.0f, 45.0f), "固定增量时间Time.fixedTime:" + Time.fixedTime);
- GUI.Label(new Rect(10.0f, 310.0f, 400.0f, 45.0f), "上一帧消耗的固定增量时间Time.fixedDeltaTime:" + Time.fixedDeltaTime);
- GUI.Label(new Rect(10.0f, 360.0f, 300.0f, 45.0f), "游戏已运行帧数Time.frameCount:" + Time.frameCount);
- }
- }
newScene01
- using UnityEngine;
- using System.Collections;
- public class RealtimeSinceStartup_ts : MonoBehaviour
- {
- public Rigidbody rg;
- void Start()
- {
- Debug.Log("Time.timeScale的默认时间:" + Time.timeScale);
- //观察刚体在timeScale变化前后的移动速度
- rg.velocity = Vector3.forward * 2.0f;
- Time.timeScale = 0.5f;
- }
- void Update()
- {
- Debug.Log("Time.timeScale的d当前值:" + Time.timeScale);
- Debug.Log("Time.time:" + Time.time);
- Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Time.timeScale=0.5f"))
- {
- Time.timeScale = 0.5f;
- }
- if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Time.timeScale=1.0f"))
- {
- Time.timeScale = 1.0f;
- }
- }
- }
RealtimeSinceStartup
- using UnityEngine;
- using System.Collections;
- public class SmoothDeltaTime_ts : MonoBehaviour
- {
- , b = ;
- bool c = false;
- void Update()
- {
- float t1, t2;
- t1 = Time.deltaTime;
- t2 = Time.smoothDeltaTime;
- Debug.Log("Time.deltaTime:" + t1);
- Debug.Log("smoothDeltaTime:" + t2);
- a += t1;
- b += t2;
- Debug.Log("Time.deltaTime的累加和:" + a + " smoothDeltaTime的累加和:" + b);
- }
- }
SmoothDeltaTime
- using UnityEngine;
- using System.Collections;
- public class Time_ts : MonoBehaviour
- {
- float t1 = 0.0f;
- void Update()
- {
- t1 = Time.deltaTime;
- }
- void OnGUI()
- {
- if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "加载新场景"))
- {
- Application.LoadLevel("newScene01_unity");
- }
- GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前游戏场景名字:" + Application.loadedLevelName);
- GUI.Label(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "当前游戏已运行时间Time.time:" + Time.time);
- GUI.Label(new Rect(10.0f, 160.0f, 400.0f, 45.0f), "当前场景已运行时间Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);
- GUI.Label(new Rect(10.0f, 210.0f, 300.0f, 45.0f), "上一帧消耗的时间Time.deltaTime:" + t1);
- GUI.Label(new Rect(10.0f, 260.0f, 300.0f, 45.0f), "固定增量时间Time.fixedTime:" + Time.fixedTime);
- GUI.Label(new Rect(10.0f, 310.0f, 400.0f, 45.0f), "上一帧消耗的固定增量时间Time.fixedDeltaTime:" + Time.fixedDeltaTime);
- GUI.Label(new Rect(10.0f, 360.0f, 300.0f, 45.0f), "游戏已运行帧数Time.frameCount:" + Time.frameCount);
- }
- }
Time_ts
12 Transform类
- using UnityEngine;
- using System.Collections;
- public class DetachChildren_ts : MonoBehaviour
- {
- void Start () {
- transform.DetachChildren();
- }
- }
DetachChildren
- using UnityEngine;
- using System.Collections;
- //将所有子物体放大2*2*2=8倍,不包括自身。
- public class Foreach_ts : MonoBehaviour {
- void Start () {
- foreach (Transform child in transform)
- {
- child.localScale *= 2.0f;
- }
- }
- }
Foreach
- using UnityEngine;
- using System.Collections;
- public class Forward_ts : MonoBehaviour {
- void Start () {
- //先给transform一个任意的欧拉角,使得transform的局部坐标系和世界坐标系方向不一致
- transform.eulerAngles = new Vector3(15.0f,30.0f,60.0f);
- //right
- Debug.Log("right:"+transform.right);
- Debug.Log("Dir:" + transform.TransformDirection(new Vector3(1.0f, 0.0f, 0.0f)));
- //up
- Debug.Log("up:" + transform.up);
- Debug.Log("Dir:" + transform.TransformDirection(new Vector3(0.0f, 1.0f, 0.0f)));
- //forward
- Debug.Log("forward:" + transform.forward);
- Debug.Log("Dir:" + transform.TransformDirection(new Vector3(0.0f, 0.0f, 1.0f)));
- }
- }
Forward
- using UnityEngine;
- using System.Collections;
- public class GetChild_ts : MonoBehaviour
- {
- void Start()
- {
- //transform的子物体数量
- int ct = transform.childCount;
- Debug.Log("子物体数量:" + ct);
- ; i < ct; i++)
- {
- Debug.Log("索引为" + i + "的子物体名字:" + transform.GetChild(i).name);
- }
- }
- }
GetChild
- using UnityEngine;
- using System.Collections;
- public class HasChanged_ts : MonoBehaviour
- {
- bool is_rotate = false;//物体旋转控制
- // Update is called once per frame
- void Update()
- {
- //当transform.hasChanged为true时打印相关信息
- if (transform.hasChanged)
- {
- Debug.Log("The transform has changed!");
- transform.hasChanged = false;
- }
- if (is_rotate)
- {
- transform.Rotate(Vector3.up * 15.0f * Time.deltaTime);
- }
- }
- void OnGUI()
- {
- //使物体开始旋转,物体rotation被修改
- if (GUI.Button(new Rect(10.0f, 10.0f, 80.0f, 45.0f), "Rotate start"))
- {
- is_rotate = true;
- }
- //停止旋转
- if (GUI.Button(new Rect(10.0f, 65.0f, 80.0f, 45.0f), "Rotate stop"))
- {
- is_rotate = false;
- }
- //将transform的当前位置赋给transform.position,也即transform的位置没有改变,
- //但是transform是position属性已经被修改,故transform.hasChanged返回值为true
- if (GUI.Button(new Rect(10.0f, 125.0f, 80.0f, 45.0f), "use position"))
- {
- is_rotate = false;
- transform.position = transform.position;
- }
- }
- }
HasChanged
- using UnityEngine;
- using System.Collections;
- public class InverseTransformDirection_ts : MonoBehaviour
- {
- void Start()
- {
- //转换前向量
- Vector3 world_v = new Vector3(10.0f, 20.0f, 30.0f);
- //transform绕y轴旋转90度,使transform坐标系与世界坐标系方向不一致
- transform.eulerAngles = new Vector3(0.0f, 90.0f, 0.0f);
- Vector3 local_v = transform.InverseTransformDirection(world_v);
- //打印transform的position,方法InverseTransformDirection与transform的position无关
- Debug.Log("transform position:" + transform.position);
- //打印transform的lossyScale,方法InverseTransformDirection与transform的lossyScale无关
- Debug.Log("transform lossyScale:" + transform.lossyScale);
- Debug.Log("world_v:" + world_v);
- Debug.Log("local_v:" + local_v);
- }
- }
InverseTransformDirection
- using UnityEngine;
- using System.Collections;
- public class InverseTransformPoint_ts : MonoBehaviour {
- Vector3 A = new Vector3(50.0f, 30.0f, 10.0f);
- Vector3 B = Vector3.zero;
- void Start()
- {
- B = transform.InverseTransformPoint(A);
- Debug.Log("transform.position:" + transform.position);
- Debug.Log("transform.lossyScale:" + transform.lossyScale);
- Debug.Log("A:" + A);
- Debug.Log("B:" + B);
- }
- }
InverseTransformPoint
- using UnityEngine;
- using System.Collections;
- public class IsChildOf_ts : MonoBehaviour
- {
- public Transform t1, t2, t3;
- void Start()
- {
- Debug.Log("t1是否为其自身的子类:" + t1.IsChildOf(t1));
- Debug.Log("t2是否为t1的子类:" + t2.IsChildOf(t1));
- Debug.Log("t3是否为t1的子类:" + t3.IsChildOf(t1));
- }
- }
IsChildOf
- using UnityEngine;
- using System.Collections;
- public class LocalPosition_ts : MonoBehaviour {
- public Transform cube0, cube1;
- void Start () {
- Debug.Log("cube0 local position:" + cube0.localPosition);
- Debug.Log("cube0 local scale:" + cube0.localScale);
- Debug.Log("cube1 local position:"+cube1.localPosition);
- Debug.Log("cube1 local scale:" + cube1.localScale);
- Debug.Log("cube2 local position:" + transform.localPosition);
- Debug.Log("cube2 world position:" + transform.position);
- }
- }
LocalPosition
- using UnityEngine;
- using System.Collections;
- public class LocalScaleOrLossyScale_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log("父物体A放缩值:" + transform.parent.localScale);
- Debug.Log("子物体B的全局有损放缩值:" + transform.lossyScale);
- Debug.Log("子物体B的局部放缩值:" + transform.localScale);
- //检验本注解部分的算法描述是否正确
- if (transform.localScale.x == (transform.lossyScale.x / transform.parent.localScale.x) &&
- transform.localScale.y == (transform.lossyScale.y / transform.parent.localScale.y) &&
- transform.localScale.z == (transform.lossyScale.z / transform.parent.localScale.z))
- {
- Debug.Log("True");
- }
- else
- {
- Debug.Log("False");
- }
- }
- }
LocalScaleOrLossyScale
- using UnityEngine;
- using System.Collections;
- public class LocalToWorldMatrix_ts : MonoBehaviour {
- void Start()
- {
- //local_vector3为transform局部坐标系中的一个向量
- Vector3 local_vector3 = new Vector3(1.0f, 2.0f, 3.0f);
- Vector3 v1 = transform.localToWorldMatrix.MultiplyPoint3x4(local_vector3);
- Debug.Log("transform position:" + transform.position);
- Debug.Log("transform lossyScale:" + transform.lossyScale);
- Debug.Log("local_vector3:" + local_vector3);
- Debug.Log("local_vector3在世界坐标系中的向量为:" + v1);
- }
- }
LocalToWorldMatrix
- using UnityEngine;
- using System.Collections;
- public class LookAt_ts : MonoBehaviour
- {
- public Transform tr_look;
- void Update()
- {
- transform.LookAt(tr_look);
- tr_look.RotateAround(Vector3.zero, Vector3.up, 60.0f * Time.deltaTime);
- }
- }
LookAt
- using UnityEngine;
- using System.Collections;
- public class Parent_ts : MonoBehaviour {
- void Start () {
- //返回transform的父物体的Transform
- Debug.Log("一级父物体名字:" + transform.parent);
- //返回transform的二级父物体的Transform
- Debug.Log("二级父物体名字:" + transform.parent.parent);
- //返回transform的三级父物体的Transform
- Debug.Log("三级父物体名字:" + transform.parent.parent.parent);
- //返回transform的最顶层(root)父物体的Transform
- Debug.Log("最顶层父物体名字:" + transform.root);
- }
- }
Parent
- using UnityEngine;
- using System.Collections;
- public class Rotate1_ts : MonoBehaviour {
- void Start () {
- //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
- transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
- transform.Rotate(new Vector3(0.0f,45.0f,0.0f),Space.Self);
- Debug.Log("Space.Self:" + transform.eulerAngles);
- //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
- transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
- transform.Rotate(new Vector3(0.0f, 45.0f, 0.0f), Space.World);
- Debug.Log("Space.World:" + transform.eulerAngles);
- //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
- transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
- transform.Rotate(new Vector3(0.0f, 45.0f, 0.0f));
- Debug.Log("默认坐标系:"+transform.eulerAngles);
- }
- }
Rotate1
- using UnityEngine;
- using System.Collections;
- public class Rotate2_ts : MonoBehaviour {
- void Start()
- {
- //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
- transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
- transform.Rotate(Vector3.up,45.0f, Space.Self);
- Debug.Log("绕自身坐标系的y轴方向旋转45度:" + transform.eulerAngles);
- //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
- transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
- transform.Rotate(Vector3.up, 45.0f, Space.World);
- Debug.Log("绕世界坐标系的y轴方向旋转45度:" + transform.eulerAngles);
- //设置transform的欧拉角,使得transform自身坐标系和世界坐标系y轴方向不一致
- transform.eulerAngles = new Vector3(30.0f, 0.0f, 0.0f);
- transform.Rotate(Vector3.up,45.0f);
- Debug.Log("绕默认坐标系的y轴方向旋转45度:" + transform.eulerAngles);
- }
- }
Rotate2
- using UnityEngine;
- using System.Collections;
- public class RotateAround_ts : MonoBehaviour {
- public Transform point_r;
- void Update () {
- transform.RotateAround(point_r.position ,Vector3.up,30.0f*Time.deltaTime);
- }
- }
RotateAround
- using UnityEngine;
- using System.Collections;
- public class TransformDirection_ts : MonoBehaviour
- {
- void Start()
- {
- Vector3 local_v = new Vector3(1.0f, 2.0f, 3.0f);
- transform.eulerAngles = new Vector3(0.0f, 90.0f, 0.0f);
- //将local_v从局部坐标系转到世界坐标系中
- Vector3 world_v = transform.TransformDirection(local_v);
- //transform的position值不影响变换结果
- Debug.Log("transform position:" + transform.position);
- //transform的lossyScale值不影响变换结果
- Debug.Log("transform lossyScale:" + transform.lossyScale);
- Debug.Log("local_v:" + local_v);
- Debug.Log("world_v:" + world_v);
- }
- }
TransformDirection
- using UnityEngine;
- using System.Collections;
- public class TransformPoint_ts : MonoBehaviour {
- Vector3 A=new Vector3(1.0f,2.0f,3.0f);
- Vector3 B=Vector3.zero;
- void Start () {
- B = transform.TransformPoint(A);
- Debug.Log("transform.position:" + transform.position);
- Debug.Log("transform.lossyScale:" + transform.lossyScale);
- Debug.Log("A:"+A);
- Debug.Log("B:"+B);
- }
- }
TransformPoint
- using UnityEngine;
- using System.Collections;
- public class Translate1_ts : MonoBehaviour {
- void Start () {
- //沿y轴旋转30度,使得transform自身坐标系和世界坐标系x轴方向不一致
- transform.eulerAngles = new Vector3(0.0f, 30.0f, 0.0f);
- //坐标位置归零
- transform.position = Vector3.zero;
- transform.Translate(new Vector3(10.0f, 0.0f, 0.0f), Space.Self);
- Debug.Log("沿自身坐标系x轴移动10个距离:" + transform.position);
- //坐标位置归零
- transform.position = Vector3.zero;
- transform.Translate(new Vector3(10.0f, 0.0f, 0.0f), Space.World);
- Debug.Log("沿世界坐标系x轴移动10个距离:" + transform.position);
- //坐标位置归零
- transform.position = Vector3.zero;
- transform.Translate(new Vector3(10.0f, 0.0f, 0.0f));
- Debug.Log("沿默认坐标系x轴移动10个距离:" + transform.position);
- }
- }
Translate1
- using UnityEngine;
- using System.Collections;
- public class Translate2_ts : MonoBehaviour {
- public Transform relativeTo;
- void Start () {
- //将relativeTo沿y轴旋转30度,使得relativeTo自身坐标系和世界坐标系x轴方向不一致
- relativeTo.eulerAngles = new Vector3(0.0f, 30.0f, 0.0f);
- //transform坐标位置归零
- transform.position = Vector3.zero;
- transform.Translate(new Vector3(10.0f, 0.0f, 0.0f), relativeTo);
- Debug.Log("沿relativeTo坐标系x轴移动10个距离:" + transform.position);
- //坐标位置归零
- transform.position = Vector3.zero;
- transform.Translate(new Vector3(10.0f, 0.0f, 0.0f));
- Debug.Log("沿默认坐标系x轴移动10个距离:" + transform.position);
- }
- }
Translate2
- using UnityEngine;
- using System.Collections;
- public class WorldToLocalMatrix_ts : MonoBehaviour {
- public Transform t1;
- void Start()
- {
- Vector3 v1 = transform.worldToLocalMatrix.MultiplyPoint3x4(t1.position);
- Debug.Log("transform position:"+transform.position);
- Debug.Log("transform lossyScale:" + transform.lossyScale);
- Debug.Log("t1 position:"+t1.position);
- Debug.Log("t1 相对transform的向量为:"+v1);
- }
- }
WorldToLocalMatrix
13 Vector2类
- using UnityEngine;
- using System.Collections;
- public class Angle_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log("1:" + Vector2.Angle(new Vector2(1.0f, 0.0f), new Vector2(-1.0f, 0.0f)));
- Debug.Log("2:" + Vector2.Angle(new Vector2(1.0f, 0.0f), new Vector2(-1.0f, -1.0f)));
- Debug.Log("3:" + Vector2.Angle(new Vector2(0.0f, 0.0f), new Vector2(-1.0f, 0.0f)));
- }
- }
Angle
- using UnityEngine;
- using System.Collections;
- public class ClampMagnitude_ts : MonoBehaviour
- {
- void Start()
- {
- Vector2 A = new Vector2(10.0f, 20.0f);
- //K值大于1时返回A的初始值
- float b = A.magnitude * 3.0f;
- Vector2 C = Vector2.ClampMagnitude(A, b);
- Debug.Log("K值大于1时返回A的初始值:" + C.ToString());
- //K值小于-1时返回A的初始值
- b = -A.magnitude * 3.0f;
- C = Vector2.ClampMagnitude(A, b);
- Debug.Log("K值小于-1时返回A的初始值:" + C.ToString());
- //K值介于-1和1之间时时按算法求值
- b = A.magnitude * 0.7f;
- C = Vector2.ClampMagnitude(A, b);
- Debug.Log("K值介于-1和1之间时时按算法求值:" + C.ToString());
- //当A为零向量时返回值永远为零向量
- A.Set(0.0f,0.0f);
- b = A.magnitude * 0.7f;
- C = Vector2.ClampMagnitude(A, b);
- Debug.Log("当A为零向量时返回值永远为零向量:" + C.ToString());
- }
- }
ClampMagnitude
- using UnityEngine;
- using System.Collections;
- public class EqualOrNot_ts : MonoBehaviour
- {
- void Start()
- {
- //A、B小数点后五位相等,第六位足够接近时返回true
- Vector2 A = new Vector2(1.123453f, 3.123453f);
- Vector2 B = new Vector2(1.123459f, 3.123459f);
- Debug.Log("First:" + (A == B));
- //A、B小数点后五位相等,但第六位不够接近时也可能返回false
- A = new Vector2(1.123451f, 3.123451f);
- Debug.Log("Second:" + (A == B));
- //A、B小数点后六位相等时一定返回true
- A = new Vector2(1.1234560f, 3.1234560f);
- B = new Vector2(1.1234569f, 3.1234569f);
- Debug.Log("Third:" + (A == B));
- }
- }
EqualOrNot
- using UnityEngine;
- using System.Collections;
- public class Lerp_ts : MonoBehaviour
- {
- void Start()
- {
- Vector2 v1 = new Vector2(4.0f, 12.0f);
- Vector2 v2 = new Vector2(9.0f, 20.0f);
- //e<0时返回值为v1的值
- Debug.Log("e<0时返回值为v1的值:" + Vector2.Lerp(v1, v2, -2.0f));
- //e>1时返回值为v2的值
- Debug.Log("e>1时返回值为v2的值:" + Vector2.Lerp(v1, v2, 2.0f));
- //e>0且e<1时按插值算法求返回值
- Debug.Log("e>0且e<1时按插值算法求返回值:" + Vector2.Lerp(v1, v2, 0.7f));
- }
- }
Lerp
- using UnityEngine;
- using System.Collections;
- public class MoveTowards_ts : MonoBehaviour
- {
- void Start()
- {
- Vector2 A = new Vector2(10.0f, 20.0f);
- Vector2 B = new Vector2(30.0f, 40.0f);
- //当K=1时返回B的值
- float sp = (B - A).magnitude;
- Vector2 C = Vector2.MoveTowards(A, B, sp);
- Debug.Log("当K=1时返回B的值:" + C.ToString());
- //当K>1时返回B的值
- sp += 10.0f;
- C = Vector2.MoveTowards(A, B, sp);
- Debug.Log("当K>1时返回B的值:" + C.ToString());
- //当K=0时返回A的值
- sp = 0.0f;
- C = Vector2.MoveTowards(A, B, sp);
- Debug.Log("当K=0时返回A的值:" + C.ToString());
- //当K<0时按算法计算
- sp = -10.0f;
- C = Vector2.MoveTowards(A, B, sp);
- Debug.Log("当K<0时按算法计算:" + C.ToString());
- //当K>0且K<1时按算法计算
- sp = (B - A).magnitude * 0.7f;
- C = Vector2.MoveTowards(A, B, sp);
- Debug.Log("当K>0且K<1时按算法计算:" + C.ToString());
- }
- }
MoveTowards
- using UnityEngine;
- using System.Collections;
- public class Normalize_ts : MonoBehaviour {
- void Start()
- {
- Vector2 v1 = new Vector2(1.0f, 2.0f);
- //使用属性不改变原始值,有返回值
- Vector2 v2 = v1.normalized;
- Debug.Log("使用属性v2.normalized后v1的值:" + v1);
- Debug.Log("使用属性v2.normalized后的返回值v2:" + v2);
- v1.Set(1.0f, 2.0f);
- //使用实例方法改变原始值,无返回值
- v1.Normalize();
- Debug.Log("使用实例方法v1.Normalize后v1的值:" + v1);
- }
- }
Normalize
- using UnityEngine;
- using System.Collections;
- public class Scale_ts : MonoBehaviour
- {
- void Start()
- {
- Vector2 v2 = new Vector2(1.0f, 2.0f);
- //实例方法会改变原始向量v2的值,无返回值
- v2.Scale(new Vector2(2.0f, 3.0f));
- Debug.Log("使用实例方法v2.Scale后v2值:" + v2);
- //使用Set方法重设v2
- v2.Set(1.0f, 2.0f);
- //类方法不会改变原始向量的值,其返回值为放缩后的向量
- Vector2 v3 = Vector2.Scale(v2, new Vector2(4.0f, 6.0f));
- Debug.Log("使用类方法Vector2.Scale后v2值:" + v2);
- Debug.Log("使用类方法Vector2.Scale后v3值:" + v3);
- }
- }
Scale
14 Vector3类
- using UnityEngine;
- using System.Collections;
- public class Angle_ts : MonoBehaviour
- {
- void Start()
- {
- Debug.Log("1:" + Vector3.Angle(Vector3.right, -Vector3.right));
- Debug.Log("2:" + Vector3.Angle(Vector3.right, -(Vector3.right + Vector3.up)));
- Debug.Log("3:" + Vector3.Angle(Vector3.right, Vector3.zero));
- }
- }
Angle
- using UnityEngine;
- using System.Collections;
- public class ClampMagnitude_ts : MonoBehaviour {
- void Start () {
- Vector3 ts = new Vector3(1.0f,2.0f,3.0f);
- Debug.Log("ts的单位向量为:"+ts.normalized+" ts模长为:"+ts.magnitude);
- Debug.Log("当f值大于ts模长时:");
- float f = ts.magnitude + 1.0f;
- Vector3 ov = Vector3.ClampMagnitude(ts,f);
- Debug.Log("ov向量:" + ov.ToString()+"其单位向量为:"+ov.normalized + " ov的模长为:" + ov.magnitude);
- Debug.Log("当f值小于ts模长时:");
- f = ts.magnitude - 1.0f;
- ov = Vector3.ClampMagnitude(ts,f);
- Debug.Log("ov向量:" + ov.ToString() + "其单位向量为:" + ov.normalized + " ov的模长为:" + ov.magnitude);
- }
- }
ClampMagnitude
- using UnityEngine;
- using System.Collections;
- public class Cross_ts : MonoBehaviour {
- public Transform A, B;
- Vector3 A_v, B_v;
- Vector3 C_v = Vector3.zero;
- void Update()
- {
- A_v = A.position;
- B_v = B.position;
- C_v = Vector3.Cross(A_v,B_v);
- Debug.DrawLine(Vector3.zero, A_v , Color.green);
- Debug.DrawLine(Vector3.zero, B_v, Color.yellow);
- Debug.DrawLine(Vector3.zero, C_v, Color.red);
- }
- }
Cross
- using UnityEngine;
- using System.Collections;
- public class Dot_ts : MonoBehaviour {
- public Transform A, B;
- Vector3 A_lv, AB_v;
- string str = "";
- void Update()
- {
- //将A的自身坐标系的forward向量转向时间坐标系中
- A_lv = A.TransformDirection(Vector3.forward);
- //A到B的差向量
- AB_v = B.position-A.position;
- float f = Vector3.Dot(A_lv, AB_v);
- ){
- str = "B在A自身坐标系的前方";
- }
- )
- {
- str = "B在A自身坐标系的后方";
- }
- else {
- str = "B在A自身坐标系的正左方或右方";
- }
- //旋转A物体使得A的自身forward方向不断改变
- //虽然A、B的世界坐标都未改变,且在世界坐标系中A和B的位置关系没有改变
- //但在A的自身坐标系中B的相对位置在不断改变
- A.Rotate(new Vector3(0.0f,1.0f,0.0f));
- }
- void OnGUI(){
- GUI.Label(new Rect(10.0f,10.0f,200.0f,60.0f),str);
- }
- }
Dot
- using UnityEngine;
- using System.Collections;
- public class EqualOrNot_ts : MonoBehaviour
- {
- void Start()
- {
- Vector3 v1 = new Vector3(1.123451f, 2.123451f, 3.123451f);
- Vector3 v2 = new Vector3(1.123452f, 2.123452f, 3.123452f);
- if (v1 == v2)
- {
- Debug.Log("v1==v2");
- }
- else
- {
- Debug.Log("v1!=v2");
- }
- }
- }
EqualOrNot
- using UnityEngine;
- using System.Collections;
- public class Lerp_ts : MonoBehaviour
- {
- public Transform start_T;//起始点位置物体
- public Transform end_T;//结束点位置物体
- Vector3 start_v, end_v;//起始和结束的两个Vector3
- float speed = 0.2f;//控制移动速度
- float last_time;//控制插值系数范围
- void Start()
- {
- start_v = start_T.position;
- end_v = end_T.position;
- last_time = Time.time;
- }
- void Update()
- {
- //利用插值改变物体位置坐标达到运动目的
- transform.position = Vector3.Lerp(start_v, end_v, (Time.time - last_time) * speed);
- if (transform.position == end_v)
- {
- //对调起始和结束点坐标
- transform.position = start_v;
- start_v = end_v;
- end_v = transform.position;
- transform.position = start_v;
- last_time = Time.time;
- }
- }
- }
Lerp
- using UnityEngine;
- using System.Collections;
- public class MoveTowards_ts : MonoBehaviour {
- public Transform from_T, to_T;
- Vector3 from_v, to_v;
- Vector3 moves = Vector3.zero;
- float speed = 0.5f;
- void Start()
- {
- //初始化起始位置
- from_v = from_T.position;
- to_v = to_T.position;
- }
- void Update()
- {
- //在向量差值to_v-from_v的模长时间内moves从from_v移动到to_v
- moves = Vector3.MoveTowards(from_v, to_v, Time.time * speed);
- //绘制从原点到slerps的红线,并保留100秒以便观察
- //运行时只能在scene视图中查看
- Debug.DrawLine(Vector3.zero, moves, Color.red, 100.0f);
- }
- }
MoveTowards
- using UnityEngine;
- using System.Collections;
- public class Normalized_ts : MonoBehaviour
- {
- void Start()
- {
- Vector3 v1 = new Vector3(1.0f, 2.0f, 3.0f);
- Vector3 v2 = v1.normalized;
- //使用v2 = v1.normalized后v1的值不会改变,而v2的值为v1的单位向量。
- Debug.Log("v2 = v1.normalized后v1的值:" + v1);
- Debug.Log("v2 = v1.normalized后v2的值:" + v2);
- //"v2 = Vector3.Normalize(v1)"与"v2 = v1.normalized"实现功能相同,但不常用。
- v2 = Vector3.Normalize(v1);
- Debug.Log("v2 = Vector3.Normalize(v1)后v1的值:" + v1);
- Debug.Log("v2 = Vector3.Normalize(v1)后v2的值:" + v2);
- //v1.Normalize()等于将v1自身进行了单位化处理,v1变成了新的向量。
- v1.Normalize();
- Debug.Log("v1.Normalize()后v1的值:" + v1);
- }
- }
Normalized
- using UnityEngine;
- using System.Collections;
- public class OrthoNormalize_ts : MonoBehaviour {
- public Transform one_T, two_T;
- Vector3 one_v, two_v;
- Vector3 one_l, two_l;
- void Start()
- {
- //初始化起始位置
- one_v = one_T.position;
- two_v = two_T.position;
- //记录初始化位置
- one_l = one_v;
- two_l = two_v;
- }
- void Update()
- {
- Vector3.OrthoNormalize(ref one_v,ref two_v);
- //绘制原始向量和OrthoNormalize处理后的向量
- Debug.DrawLine(Vector3.zero, one_l, Color.black);
- Debug.DrawLine(Vector3.zero, two_l, Color.white);
- Debug.DrawLine(Vector3.zero, one_v, Color.red);
- Debug.DrawLine(Vector3.zero, two_v, Color.yellow);
- }
- }
OrthoNormalize
- using UnityEngine;
- using System.Collections;
- public class OrthoNormalize2_ts : MonoBehaviour {
- public Transform one_T, two_T, three_T;
- Vector3 one_v, two_v, three_v;
- Vector3 one_l, two_l, three_l;
- void Start()
- {
- //初始化起始位置
- one_v = one_T.position;
- two_v = two_T.position;
- three_v = three_T.position;
- //保持初始值
- one_l = one_v;
- two_l = two_v;
- three_l = three_v;
- }
- void Update()
- {
- Vector3.OrthoNormalize(ref one_v, ref two_v,ref three_v);
- //绘制原始向量和OrthoNormalize处理后的向量
- Debug.DrawLine(Vector3.zero, one_l, Color.black);
- Debug.DrawLine(Vector3.zero, two_l, Color.white);
- Debug.DrawLine(Vector3.zero, three_l, Color.green);
- Debug.DrawLine(Vector3.zero, one_v, Color.red);
- Debug.DrawLine(Vector3.zero, two_v, Color.yellow);
- Debug.DrawLine(Vector3.zero, three_v, Color.blue);
- }
- }
OrthoNormalize2
- using UnityEngine;
- using System.Collections;
- public class Project_ts : MonoBehaviour {
- public Transform from_T, to_T;
- Vector3 projects = Vector3.zero;
- void Update()
- {
- projects = Vector3.Project(from_T.position, to_T.position);
- Debug.DrawLine(Vector3.zero, projects, Color.black);
- Debug.DrawLine(Vector3.zero, from_T.position, Color.red);
- Debug.DrawLine(Vector3.zero, to_T.position, Color.yellow);
- }
- }
Project
- using UnityEngine;
- using System.Collections;
- public class Reflect_ts : MonoBehaviour
- {
- public Transform A, B;
- //A_v为镜面向量,B_v为入射向量
- Vector3 A_v, B_v;
- //R_v为反射向量
- Vector3 R_v = Vector3.zero;
- void Update()
- {
- //将镜面向量进行单位化处理,否则反射向量不一定为镜面反射
- A_v = A.position.normalized;
- B_v = B.position;
- R_v = Vector3.Reflect(B_v, A_v);
- Debug.DrawLine(-A_v * 1.5f, A_v *1.5f, Color.black);
- Debug.DrawLine(Vector3.zero, B_v, Color.yellow);
- Debug.DrawLine(Vector3.zero, R_v, Color.red);
- }
- }
Reflect
- using UnityEngine;
- using System.Collections;
- public class RotateTowards_ts : MonoBehaviour
- {
- public Transform from_T, to_T;
- Vector3 from_v, to_v;
- Vector3 rotates = Vector3.zero;
- float speed = 0.2f;
- float l;
- void Start()
- {
- //初始化起始位置
- from_v = from_T.position;
- to_v = to_T.position;
- //l取值为0时,rotates会以from_v的模长运动到to_v方向
- // l = 0.0f;
- //l取值为(to_v - from_v).sqrMagnitude时,rotates会以to_v的模长运动到to_v方向
- l = (to_v - from_v).sqrMagnitude;
- }
- void Update()
- {
- //在1/speed时间内rotates从from_v移动到to_v
- rotates = Vector3.RotateTowards(from_v, to_v, Time.time*speed,l);
- //绘制从原点到slerps的红线,并保留100秒以便观察
- //运行时只能在scene视图中查看
- Debug.DrawLine(Vector3.zero, rotates, Color.red, 100.0f);
- }
- }
RotateTowards
- using UnityEngine;
- using System.Collections;
- public class Scale_ts : MonoBehaviour
- {
- void Start()
- {
- Vector3 v1 = new Vector3(1.0f, 2.0f, 3.0f);
- Vector3 v2 = new Vector3(4.0f, 5.0f, 6.0f);
- //使用v1.Scale(v2)将使向量v1按向量v2进行放缩,无返回值
- v1.Scale(v2);
- Debug.Log("使用v1.Scale(v2)后v1的值:" + v1.ToString());
- Debug.Log("使用v1.Scale(v2)后v2的值:" + v2.ToString());
- //重设v1
- v1.Set(1.0f, 2.0f, 3.0f);
- //使用v3 = Vector3.Scale(v1, v2)将会返回向量v1按向量v2进行放缩后的向量v3
- //v1、v2不会改变
- Vector3 v3 = Vector3.Scale(v1, v2);
- Debug.Log("使用v3=Vector3.Scale(v1,v2)后v1的值:" + v1.ToString());
- Debug.Log("使用v3=Vector3.Scale(v1,v2)后v2的值:" + v2.ToString());
- Debug.Log("使用v3=Vector3.Scale(v1,v2)后v3的值:" + v3.ToString());
- }
- }
Scale
- using UnityEngine;
- using System.Collections;
- public class Slerp_ts : MonoBehaviour {
- public Transform from_T, to_T;
- Vector3 from_v, to_v;
- Vector3 slerps = Vector3.zero;
- float speed = 0.1f;
- void Start () {
- //初始化起始位置
- from_v = from_T.position;
- to_v = to_T.position;
- }
- void Update () {
- //在1/speed时间内slerps从from_v移动到to_v
- slerps = Vector3.Slerp(from_v,to_v,Time.time*speed);
- //绘制从原点到slerps的红线,并保留100秒以便观察
- //运行时只能在scene视图中查看
- Debug.DrawLine(Vector3.zero,slerps,Color.red,100.0f);
- }
- }
Slerp
- using UnityEngine;
- using System.Collections;
- public class SmoothDamp_ts : MonoBehaviour {
- public Transform from_T, to_T;
- public float smoothTime, maxSpeed,delta_time;
- Vector3 to_v;
- Vector3 speed = Vector3.zero;
- void Start()
- {
- //初始化起始位置
- transform.position = from_T.position;
- to_v = to_T.position;
- //初始化系数
- smoothTime = 1.5f;
- maxSpeed = 10.0f;
- delta_time = 1.0f;
- }
- void Update()
- {
- transform.position = Vector3.SmoothDamp(transform.position, to_v, ref speed, smoothTime, maxSpeed, Time.deltaTime * delta_time);
- }
- }
SmoothDamp
- using UnityEngine;
- using System.Collections;
- public class SqrMagnitude_ts : MonoBehaviour {
- void Start () {
- Vector3 v1 = new Vector3(3.0f,4.0f,5.0f);
- Vector3 v2 = new Vector3(1.0f, 2.0f, 8.0f);
- Debug.Log("向量v1的长度:"+v1.magnitude);
- Debug.Log("向量v2的长度:"+v2.magnitude);
- float f1 = v1.sqrMagnitude;
- float f2 = v2.sqrMagnitude;
- Debug.Log("v1模长的平方值:" + f1 + " v2模长的平方值:" + f2);
- if(f1 == f2){
- Debug.Log("向量v1和v2的模长一样大!");
- }
- else if (f1 > f2)
- {
- Debug.Log("向量v1的模长比较大!");
- }else{
- Debug.Log("向量v2的模长比较大!");
- }
- }
- }
SqrMagnitude
Unity API 解析 (陈泉宏著)的更多相关文章
- Unity API 解析(13)—— Vector3 类
三维向量或三维坐标点 normalized —— 单位化向量 返回方向相同模长为1的向量 sqrMagnitude —— 模长平方 Scale —— 向量缩放 Angle —— 两向量夹角 Cross ...
- java微信开发API解析(二)-获取消息和回复消息
java微信开发API解析(二)-获取消息和回复消息 说明 * 本演示样例依据微信开发文档:http://mp.weixin.qq.com/wiki/home/index.html最新版(4/3/20 ...
- 源生API解析XML文档与dom4j解析XML文档
一.XML语言 XML是一种可扩展的标记语言,是一种强类型的语言,类似HTML(超文本标记语言,是一种弱类型的语言).XML是一种通用的数据交换格式(关系型数据库),综上所诉:XML可以传输数据,也可 ...
- 使用JAVA API 解析ORC File
使用JAVA API 解析ORC File orc File 的解析过程中,使用FileInputFormat的getSplits(conf, 1)函数, 然后使用 RecordReaderreade ...
- Activiti学习笔记5 — 常用API解析
常用API解析: 一.ProcessEngineConfiguration 流程引擎配置对象(配置数据库连接4个大配置和建表策略) 二.ProcessEngine 流程引擎核心对象( ...
- JavaScript 对象所有API解析【2020版】
JavaScript 对象所有API解析[2020版] 写于 2019年08月20日,虽然是2019年写的文章,但现在2020年依旧不过时,现在补充了2019年新增的ES10 Object.fromE ...
- Winform实现用多线程、百度地图API解析某公司的物理地址
前言 作为一个很挫的C#新手总喜欢自己写点儿不着边际的东西,本人是个新手加菜鸟,写B/S的,工作中,任务完成了,空闲下来,总想继续学点儿什么,由此触发了本篇文章了.个人一直认为,.NET中,C/S所要 ...
- unity文件解析以及版本控制
刚开始使用unity做开发时,拿到一个范例工程先上传SVN,之后再自己做一些修改后,发现有非常多文件都有变化,这才知道有很多本地生成的文件,是不用上传的,但是不知道哪些才是需要共用的.之后又困扰于修改 ...
- Unity各平台内置宏定义
属性 方法 UNITY_EDITOR #define directive for calling Unity Editor scripts from your game code. UNITY_EDI ...
随机推荐
- table-cell 布局
table-cell能实现段落文字相对于div的垂直居中: 将div设置为display:table-cell; *display:inline-block;text-align:center; ve ...
- 1085 PAT单位排行
每次 PAT 考试结束后,考试中心都会发布一个考生单位排行榜.本题就请你实现这个功能. 输入格式: 输入第一行给出一个正整数 N(≤10^5),即考生人数.随后 N 行,每行按下列格式给出一个考 ...
- DevExpress v18.1新版亮点——Reporting篇(一)
用户界面套包DevExpress v18.1日前终于正式发布,本站将以连载的形式为大家介绍各版本新增内容.本文将介绍了DevExpress Reporting v18.1 的新功能,快来下载试用新版本 ...
- system v ipc的标识符ID
system v ipc对象是靠标识符ID来识别和操作的,具有系统唯一性.意思就是说,该ID是操作系统内的全局变量,只要具有权限,任何进程都可以通过标识符进行进程间的通信.获取标识符ID的函数为int ...
- L256 翻译
Should work be placed among the causes of happiness or be regarded as a burden? Much work isexceedin ...
- 【转】CEF3加载网页---多字节字符集和UNICODE字符集
static char* MBSCToCEF(const char* mbcsStr) { wchar_t* wideStr; char* utf8Str; int charLen; charLen ...
- LVS原理详解(3种工作方式8种调度算法)
一.集群简介 什么是集群 计算机集群简称集群是一种计算机系统,它通过一组松散集成的计算机软件和/或硬件连接起来高度紧密地协作完成计算工作.在某种意义上,他们可以被看作是一台计算机.集群系统中的单个计算 ...
- RIP路由协议(一)
实验要求:使用RIPv2配置路由器,使路由器能接收到所有的路由条目 拓扑如下: 配置如下: R1enable 进入特权模式configure terminal 进入全局模式interface s0/0 ...
- 机器学习: 共轭梯度算法(PCG)
今天介绍数值计算和优化方法中非常有效的一种数值解法,共轭梯度法.我们知道,在解大型线性方程组的时候,很少会有一步到位的精确解析解,一般都需要通过迭代来进行逼近,而 PCG 就是这样一种迭代逼近算法. ...
- Opencv-Python 图像透视变换cv2.warpPerspective
# -*- coding:utf-8 -*- import cv2 import numpy as np import sys img = cv2.imread('test.jpg') # cv2.i ...