Unity3D 一个设置方向键移动和空格起跳的脚本


Unity3D 一个设置方向键移动和空格起跳的脚本:

  1. /// This script moves the character controller forward    
  2. /// and sideways based on the arrow keys.   
  3. /// It also jumps when pressing space.   
  4. /// Make sure to attach a character controller to the same game object.   
  5. /// It is recommended that you make only one call to Move or SimpleMove per frame.       
  6.   
  7. var speed : float = 6.0;  
  8. var jumpSpeed : float = 8.0;  
  9. var gravity : float = 20.0;  
  10.   
  11. private var moveDirection : Vector3 = Vector3.zero;  
  12.   
  13. function Update() {  
  14.     var controller : CharacterController = GetComponent(CharacterController);  
  15.     if (controller.isGrounded) {  
  16.         // We are grounded, so recalculate   
  17.         // move direction directly from axes   
  18.         moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,  
  19.                                 Input.GetAxis("Vertical"));   
  20.         // 这里获取了键盘的前后左右的移动,但注意,这是相对于自己的。   
  21.         moveDirection = transform.TransformDirection(moveDirection);   
  22.         // 还有一个TransformPoint。这里是把相对于自己的   
  23.         // 坐标转换为相对于世界的坐标。   
  24.         moveDirection *= speed;  
  25.           
  26.         if (Input.GetButton ("Jump")) {  
  27.             moveDirection.y = jumpSpeed;  
  28.         }  
  29.     }  
  30.   
  31.     // Apply gravity   
  32.     moveDirection.y -= gravity * Time.deltaTime;  
  33.       
  34.     // Move the controller   
  35.     controller.Move(moveDirection * Time.deltaTime);  
  36. }  

这段代码来自Unity3D的官方文档。

相关内容