功能区别:
a. useGravity属性是确定刚体是否接受重力加速度的感应。
b. isKinematic属性是确定刚体是否接受动力学模拟,此影响不仅包括重力感应,还包括速度、阻力、质量等的物理模拟。
举例说明:如图10-19所示,A和B为两个刚体物体,A在B的正上方,开始时A和B的重力感应都被关闭,都处于静止状态,且接受动力学模拟即isKinematic为false。现在开启A的重力感应,则A从1处开始加速下落,当下落到2处时,关闭A的重力感应,但isKinematic依然为false(即接受动力学模拟),则A将以当前速度匀速下落。但是此时若关闭物理感应,即isKinematic=true,则A将立即停止移动。当A与B发生碰撞时,若B的重力感应依然关闭,但接受动力学模拟,即isKinematic=false,则根据动量守恒B将产生一个向下的速度。但是若关闭B物体的动力学模拟,即isKinematic=true,则B保持静止,不会因受到A的碰撞而下落。
在Unity中在刚体不与其他物体接触的情况下velocity的值只与Gravity、drag及Kinematic有关,与质量mass及物体的Scale值无关。
实例演示:下面通过实例演示useGravity、isKinematic和velocity的使用。
- 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;
- }
- }
- }
在这段代码中,首先声明了两个Rigidbody类变量A和B,用于指向场景中物体,然后在Start方法中对A、B的useGravity、isKinematic及position进行初始化,最后在OnGUI方法中定义了4个Button用于演示useGravity、isKinematic和velocity的关系。程序运行情况请参考功能说明部分,请读者自行运行程序,查看不同状态下变量A、B所指向物体的运动状态。
本文章内容摘自图书《Unity API解析》,源码下载地址:http://www.ituring.com.cn/book/1474
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。