本節(jié)要點
#1.變換組件運動特點
使用 Transform.Translate()方法移動物體的位置,特點如下:
①移動的物體會“穿透”場景中其他的物體模型;
②移動的物體不會受重力影響(到達場景邊緣外,不會下落)。
#2.剛體組件簡介
1.剛體簡介
剛體:Rigidbody,屬于物理類組件。
作用:添加了剛體組件的游戲物體,就有了重力,就會做自由落體運動。也就意
味著可以像現(xiàn)實中的物體一樣運動。
2.給物體添加剛體組件
選中游戲物體-->菜單 Component-->Physics-->Rigidbody
#3.剛體組件屬性
1.Mass[質(zhì)量]
設(shè)置物體的質(zhì)量,也就是重量。質(zhì)量單位是 KG。
2.Drag[阻力]
空氣阻力,0 表示無阻力,值很大時物體會停止運動。
3.Angular Drag[角阻力]
受到扭曲力時的空氣阻力,0 表示無阻力,值很大時物體會停止運動。
4.Use Gravity[使用重力]
是否使用重力。
#4.使用剛體移動物體
1.相關(guān)方法
Rigidbody.MovePosition(Vector3):使用剛體移動物體的位置。
使用剛體移動物體,物體是根據(jù)世界坐標系的方向移動的。
使用剛體移動物體,物體會觸發(fā)物理相關(guān)的事件。
2.參數(shù)
MovePosition 中的 Vector3 要使用“當前位置”+ 方向 的方式。
Transform.Position:屬性 當前物體的位置。
3.特點
使用剛體移動物體,特點如下:
①會于場景中的模型物體發(fā)生碰撞;
②會受重力影響(到達場景邊緣外,會下落)。
場景視圖

關(guān)鍵代碼
InputTest
public class InputTest : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//鍵盤的值
//按下A鍵持續(xù)返回true
if (Input.GetKey(KeyCode.A))
{
Debug.Log("Get...........A");
}
//按下A鍵瞬間返回true
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("Getkeydown...........A Down!");
}
//松開A鍵瞬間返回true
if (Input.GetKeyUp(KeyCode.A))
{
Debug.Log("Getkeyup..............A Up!");
}
//鼠標的值
//獲取鼠標的按鍵,持續(xù)返回true
if (Input.GetMouseButton(0))
{
Debug.Log("Mouse Left");
}
//點擊鼠標按鍵瞬間返回true
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Left Down!");
}
//松開鼠標瞬間返回true
if (Input.GetMouseButtonUp(0))
{
Debug.Log("Left Up!");
}
}
}
StudentMove
public class StudentMove : MonoBehaviour {
private Transform m_Transform;
// Use this for initialization
void Start () {
//獲取相應(yīng)組件的引用,聲明同類型字段去接收
m_Transform=gameObject.GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
//移動物體位置的關(guān)鍵語句
// m_Transform.Translate(Vector3.forward*0.1f,Space.World);
//參數(shù)1:Vector3移動物體的三維變量(枚舉類型),表示x,y,z;Space參數(shù)2:移動物體的坐標系(枚舉類型)自身坐標系或世界坐標系
//0.1f 表示將當前速度下調(diào)到原來十分之一;切記加上f
//獲取相應(yīng)鍵控制方向;w a s d
if (Input.GetKey(KeyCode.W))
{
m_Transform.Translate(Vector3.forward*0.1f,Space.World);//往前
}
if (Input.GetKey(KeyCode.S))
{
m_Transform.Translate(Vector3.back * 0.1f, Space.World);//向后
}
if (Input.GetKey(KeyCode.A))
{
m_Transform.Translate(Vector3.left * 0.1f, Space.World);//向左
}
if (Input.GetKey(KeyCode.D))
{
m_Transform.Translate(Vector3.right * 0.1f, Space.World);//向右
}
}
}
小結(jié)

游戲物體與組件.png

瘋狂的小鳥.jpg

Unity API.png