Unity3D範例之1.FPSWalker
FPSWalker.cs
using UnityEngine; using System.Collections; [RequireComponent(typeof(CharacterController))] //js->@script RequireComponent(CharacterController) public class FPSWalker : MonoBehaviour { //請不要在這裡就將參數初始化 public float speed = 6.0f; public float jumpSpeed = 8.0f; public float gravity = 20.0f; private Vector3 moveDirection = Vector3.zero; private bool grounded = false; // Use this for initialization void Start () { //一定要在Start或Awake裡面做初始化,這樣才不會有參數值更改無效的問題 speed = 6.0f; jumpSpeed = 8.0f; gravity = 20.0f; moveDirection = Vector3.zero; grounded = false; } // Update is called once per frame void FixedUpdate () { if(grounded){ //取得自身座標 moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")); //轉換自身座標為世界座標 moveDirection = transform.TransformDirection(moveDirection); //x,y,z向量值乘與speed moveDirection *= speed; //有按到Edit-Project Settings-Input中Jump所定義的按鍵 if(Input.GetButton("Jump")){ moveDirection.y = jumpSpeed; } } //重力效果 moveDirection.y -= gravity * Time.deltaTime; //取得腳色控制 CharacterController controller = GetComponent(); //移動腳色 CollisionFlags flags = controller.Move(moveDirection*Time.deltaTime); //是否還有接觸地面 grounded = ((flags & CollisionFlags.CollidedBelow) != 0); /* 另一種寫法 CharacterController controller = GetComponent(); if(controller.isGrounded){ moveDirection = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical")); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= speed; //operator * if(Input.GetButton("Jump")){ moveDirection.y = jumpSpeed; } } moveDirection.y -= gravity * Time.deltaTime; controller.Move(moveDirection*Time.deltaTime); */ } }
留言
張貼留言