一、Rigidbody(剛體)
Unity 中的 物理引擎能夠真實的模擬現實世界的物理效果,在 Unity 中使用的是 NVIDIA 的 PhysX 物理引擎,在 Unity 中使用 Rigidbody 讓游戲對象受物理引擎控制。
打開 Unity ,新建一個 Plane,將它的 transform reset 一下,讓它處在原點的位置。為了方便查看,可以給這個 Plane 添加一個材質球,設置一個顏色,然后創建一個 Cube 物體,
運行游戲,并不會有什么變化。
然后,給 Cube 物體添加 Rigidbody 屬性:
plane.png
再重新運行游戲,如下圖:
運行結果
會發現 Cube 物體受到重力的影響,落到 Plane 上。
然后在看一下 Rigidbody 屬性:
mass :質量,默認為 1
Drag :空氣阻力,默認為 0
Angular Drag :當物體旋轉時收到的阻力,默認為 0.05
Use Grivity :是否使用重力,默認選中
Is Kineatic :是否使用運動學,默認不選中(和 transform 不能同時使用),如果選中,則不會受到重力影響
Interpolate :差值,None(無),Interpolate(內差值,從之前的一幀,推測下一幀的位置),Extrapolate(外差值,從下一幀推測上一幀位置),
Collision Detection :碰撞檢測,Discrete(離散檢測),Continuous(連續碰撞檢測),Continuous Dynamic(連續動態碰撞檢測)
Constraints :約束
Freeze Position :凍結位置,如果勾選 y,則不會下落
Freeze Rotation :凍結旋轉
rigidbody屬性
接著創建一個 Sphere 物體,給它添加剛體屬性,然后運行,之后用 Sphere 碰撞 Cube:
運行結果
如果凍結旋轉屬性,則落到 Plane 上之后,就不會發生旋轉了。
接著選中 Cube ,給 Cube 添加一個腳本,添加下面的代碼,可以獲取屬性面板里的所有屬性:
Rigidbody rb = GetComponent <Rigidbody>();
float mass = rb.mass;
float drag = rb.drag;
// ...
二、剛體和碰撞體
1.剛體
using UnityEngine;
using System.Collections;
public class cubeScript : MonoBehaviour {
private Rigidbody rb;
// Use this for initialization
void Start () {
rb = GetComponent <Rigidbody>();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Alpha1)) {
// 給當前游戲對象添加一個力
// rb.AddForce (new Vector3(0.0f, 10.0f, 0.0f));
// 給當前游戲對象添加 力矩/扭矩,扭矩可以使物體旋轉
// rb.AddTorque (new Vector3(0.0f, 10.0f, 0.0f));
// 給當前游戲對象在指定的位置上添加一個力
// rb.AddForceAtPosition (new Vector3(0.0f, 10.0f, 0.0f), new Vector3(0.5f, 0.5f, 0.5f));
// 給當前游戲對象在某個點添加一個爆炸力,不能持續添加,只能炸一下
rb.AddExplosionForce (1500.0f, Vector3.zero, 5.0f);
}
}
}
運行效果如下:
![Upload 碰撞.gif failed. Please try again.]
2.Collider
Collider 組件的主要功能是進行碰撞檢測,使用剛體時,一般都會和 Collider 共同使用。
創建游戲物體時都會默認創建一個 Box Collider (盒型碰撞器),在 Cube 的邊框上,主要作用是界定一個范圍,也就是一個包圍盒,來檢測是否發生碰撞
盒型碰撞器
Is Trigger :是否具有觸發效果,默認不選中
Material : 物理材質(摩擦力,彈力)
Center :邊框的位置
Size :邊框的大小
移動Box的center.gif
3.碰撞和觸發事件
發生碰撞的兩個物體必須帶有 Collider ,發生碰撞的兩個物體至少有一個帶有剛體,發生碰撞的兩個物體必須有相對運動。
using UnityEngine;
using System.Collections;
public class redScript : MonoBehaviour {
// Use this for initialization
void Start () {
//
}
// Update is called once per frame
void Update () {
}
// 觸發器的三個事件
// 進入觸發范圍會調用一次
void onTriggerEnter (Collider other) {
}
// 當持續在觸發范圍內發生時調用
void onTriggerStay (Collider other) {
}
// 離開觸發范圍會調用一次
void onTriggerExit (Collider other) {
}
// -------
//碰撞相關的三個方法
// 碰撞開始會調用一次
void onCollisionEnter (Collision other) {
}
// 當碰撞持續發生時調用
void onCollisionStay (Collision other) {
//檢測和誰發生碰撞
if (string.Equals ("Cube2", other.gameObject.name)) {
print("產生了火花");
}
}
// 碰撞結束會調用一次
void onCollisionExit (Collision other) {
}
}