Unity 3D 中实现对物体 位置(position) 旋转(rotation) 大小(scale) 的全面控制

今天分享一些基础控制的脚本

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 }

 

posted @ 2016-09-19 11:07  乔高建  阅读(23588)  评论(0编辑  收藏  举报