今天分享一些基礎控制的腳本
1.位置(Position):
控制位置很簡單,首先要知道要在xyz哪幾個軸上移動,確定好后定義代表着那些軸的移動變量,速度(m_speed在函數外定義為全局變量)然后通過if語句實現特定鍵對偏移量的增減,最后通過transform.translate實現移動 這些腳本要放在Update里
1 //在x和z軸的移動量 2 float movez = 0; 3 float movex = 0; 4 //實現移動控制 5 if (Input.GetKey(KeyCode.UpArrow)||Input.GetKey(KeyCode.W)) 6 { 7 movez += m_speed * Time.deltaTime; 8 } 9 if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S)) 10 { 11 movez -= m_speed * Time.deltaTime; 12 } 13 if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A)) 14 { 15 movex -= m_speed * Time.deltaTime; 16 } 17 if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D)) 18 { 19 movex += m_speed * Time.deltaTime; 20 } 21 m_transform.Translate(new Vector3(movex, 0, movez));
2.旋轉(Rotation):
1 float speed = 100.0f; 2 float x; 3 float z; 4 5 void Update () { 6 if(Input.GetMouseButton(0)){//鼠標按着左鍵移動 7 y = Input.GetAxis("Mouse X") * Time.deltaTime * speed; 8 x = Input.GetAxis("Mouse Y") * Time.deltaTime * speed; 9 }else{ 10 x = y = 0 ; 11 } 12 13 //旋轉角度(增加) 14 transform.Rotate(new Vector3(x,y,0)); 15 /**---------------其它旋轉方式----------------**/ 16 //transform.Rotate(Vector3.up *Time.deltaTime * speed);//繞Y軸 旋轉 17 18 //用於平滑旋轉至自定義目標 19 pinghuaxuanzhuan(); 20 } 21 22 23 //平滑旋轉至自定義角度 24 25 void OnGUI(){ 26 if(GUI.Button(Rect(Screen.width - 110,10,100,50),"set Rotation")){ 27 //自定義角度 28 29 targetRotation = Quaternion.Euler(45.0f,45.0f,45.0f); 30 // 直接設置旋轉角度 31 //transform.rotation = targetRotation; 32 33 // 平滑旋轉至目標角度 34 iszhuan = true; 35 } 36 } 37 38 bool iszhuan= false; 39 Quaternion targetRotation; 40 41 void pinghuaxuanzhuan(){ 42 if(iszhuan){ 43 transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 3); 44 } 45 }
3.大小(Scale):
1 float speed = 5.0f; 2 float x; 3 float z; 4 5 void Update () { 6 x = Input.GetAxis("Horizontal") * Time.deltaTime * speed; //水平 7 z = Input.GetAxis("Vertical") * Time.deltaTime * speed; //垂直//"Fire1","Fine2","Fine3"映射到Ctrl,Alt,Cmd鍵和鼠標的三鍵或腰桿按鈕。新的輸入軸可以在Input Manager中添加。 8 transform.localScale += new Vector3(x, 0, z); 9 10 /**---------------重新設置角度(一步到位)----------------**/ 11 //transform.localScale = new Vector3(x, 0, z); 12 }