Unity3D 一個設置方向鍵移動和空格起跳的腳本:
- /// This script moves the character controller forward
- /// and sideways based on the arrow keys.
- /// It also jumps when pressing space.
- /// Make sure to attach a character controller to the same game object.
- /// It is recommended that you make only one call to Move or SimpleMove per frame.
-
- var speed : float = 6.0;
- var jumpSpeed : float = 8.0;
- var gravity : float = 20.0;
-
- private var moveDirection : Vector3 = Vector3.zero;
-
- function Update() {
- var controller : CharacterController = GetComponent(CharacterController);
- if (controller.isGrounded) {
- // We are grounded, so recalculate
- // move direction directly from axes
- moveDirection = Vector3(Input.GetAxis("Horizontal"), 0,
- Input.GetAxis("Vertical"));
- // 這裡獲取了鍵盤的前後左右的移動,但注意,這是相對於自己的。
- moveDirection = transform.TransformDirection(moveDirection);
- // 還有一個TransformPoint。這裡是把相對於自己的
- // 坐標轉換為相對於世界的坐標。
- moveDirection *= speed;
-
- if (Input.GetButton ("Jump")) {
- moveDirection.y = jumpSpeed;
- }
- }
-
- // Apply gravity
- moveDirection.y -= gravity * Time.deltaTime;
-
- // Move the controller
- controller.Move(moveDirection * Time.deltaTime);
- }
這段代碼來自Unity3D的官方文檔。