unity3d 移动与旋转 1

移动与旋转 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     }

 

转载于:https://www.cnblogs.com/88999660/p/3707168.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值