歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Unity3D 一個設置方向鍵移動和空格起跳的腳本

Unity3D 一個設置方向鍵移動和空格起跳的腳本

日期:2017/3/1 10:15:54   编辑:Linux編程

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. var speed : float = 6.0;
  7. var jumpSpeed : float = 8.0;
  8. var gravity : float = 20.0;
  9. private var moveDirection : Vector3 = Vector3.zero;
  10. function Update() {
  11. var controller : CharacterController = GetComponent(CharacterController);
  12. if (controller.isGrounded) {
  13. // We are grounded, so recalculate
  14. // move direction directly from axes
  15. moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
  16. Input.GetAxis("Vertical"));
  17. // 這裡獲取了鍵盤的前後左右的移動,但注意,這是相對於自己的。
  18. moveDirection = transform.TransformDirection(moveDirection);
  19. // 還有一個TransformPoint。這裡是把相對於自己的
  20. // 坐標轉換為相對於世界的坐標。
  21. moveDirection *= speed;
  22. if (Input.GetButton ("Jump")) {
  23. moveDirection.y = jumpSpeed;
  24. }
  25. }
  26. // Apply gravity
  27. moveDirection.y -= gravity * Time.deltaTime;
  28. // Move the controller
  29. controller.Move(moveDirection * Time.deltaTime);
  30. }

這段代碼來自Unity3D的官方文檔。

Copyright © Linux教程網 All Rights Reserved