unity3d 移動與旋轉 1

星塵發表於2014-05-04

移動與旋轉 1

 

player角色隨asdw按鍵左右上下移動並旋轉

 

 1 public void Update()
 2     {            
 3         // Reset player rotation to look in the same direction as the camera.
 4         Quaternion tempRotation = myCamera.transform.rotation;
 5         tempRotation.x = 0;
 6         tempRotation.z = 0;        
 7         myTransform.rotation = tempRotation;
 8         
 9         float xMovement = Input.GetAxis("Horizontal");// The horizontal movement.
10         float zMovement = Input.GetAxis("Vertical");// The vertical movement.
11                 
12         // Are whe grounded, yes then move.
13         if (IsGrounded()) {
14             
15             //Move player the same distance in each direction. Player must move in a circular motion.
16             float tempAngle = Mathf.Atan2(zMovement,xMovement);  //獲取到鍵盤輸入的弧度
17 
18             xMovement *= Mathf.Abs(Mathf.Cos(tempAngle));//將鍵盤座標系的弧度轉換為新座標系的x座標(當斜邊為1時cos弧度求到x)
19             zMovement *= Mathf.Abs(Mathf.Sin(tempAngle));//同理求到y
20 
21             moveDirection = new Vector3(xMovement, 0, zMovement); //得到方向
22 
23             moveDirection = myTransform.TransformDirection(moveDirection);
24             moveDirection *= moveSpeed;
25             
26             // Make the player jump.
27             if (Input.GetButton("Jump"))
28                {
29                 moveDirection.y = jumpSpeed; //跳躍
30                 // TODO Add jump animation.
31                }            
32            }
33         
34         // Apply gravity.
35         moveDirection.y -= gravity * Time.deltaTime; //重力
36                     
37         // Are we moving.
38         if(moveDirection.x == 0 && moveDirection.z == 0)
39         {
40             if(animator!=null)
41             {
42                 animator.SetBool("run", false);    //停止移動後停止播放動畫        
43             }
44         }
45         else
46         {
47             // Make rotation object(The child object that contains animation) rotate to direction we are moving in.
48             Vector3 temp = myTransform.position;
49             temp.x += xMovement; //得到下一個目標點
50             temp.z += zMovement;        
51             myRotationObject.localRotation = Quaternion.Slerp(myRotationObject.localRotation, Quaternion.LookRotation(temp-myTransform.position), rotationSpeed * Time.deltaTime);    //使角色平滑轉向下一個目標點
52             if(animator!=null)
53             {
54                 animator.SetBool("run", true); 
55             }
56         }
57             
58         controller.Move(moveDirection * Time.deltaTime); //開始移動                    
59     }

 

相關文章