1 //設置地圖邊界:1:建立一個類 Boundary(邊界) 2 public class Boundary 3 { 4 public float xMin; 5 public float xMax; 6 public float zMin; 7 public float zMax; 8 } 9 public Transform m_Transform; 10 private Rigidbody m_Rigidbody; 11 public Boundary boundary; 12 void Start () { 13 m_Transform = gameObject.GetComponent<Transform>(); 14 m_Rigidbody = gameObject.GetComponent<Rigidbody>(); 15 //實例化 Bundary 類 ,並給這些變量賦值; 16 boundary = new Boundary() { xMin = -3f, xMax = 3f, zMin = -3f, zMax = 3f }; 19 } 20 21 void Update () { 22 23 float fmh = Input.GetAxis("Horizontal");//獲得水平移量 24 float fmv = Input.GetAxis("Vertical"); //獲得垂直移量 25 Vector3 move = new Vector3(fmh,0,fmv); //造成三維向量 26 27 28 if (m_Rigidbody!=null) 29 { 30 m_Rigidbody.velocity = move *10; //獲得剛體的速度 31 32 //限制剛體的移動範圍 Mathf.Clamp 一個範圍 33 float fx = Mathf.Clamp(m_Rigidbody.position.x,boundary.xMin,boundary.xMax); 34 float fz = Mathf.Clamp(m_Rigidbody.position.z,boundary.zMin,boundary.zMax); 35 36 m_Rigidbody.position = new Vector3(fx,0.0F,fz); 37 38 39 ///物體的傾斜角度 40 m_Rigidbody.rotation = Quaternion.Euler(0.0F,0.0F,m_Rigidbody.velocity.x*5f); 41 42 43 } 44 45 46 } 47 }