1. 程式人生 > >unity3D 第一人稱WASD+SPACE,帶重力,碰撞檢測,FPSInput.cs,P40

unity3D 第一人稱WASD+SPACE,帶重力,碰撞檢測,FPSInput.cs,P40

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(CharacterController))]
[AddComponentMenu("Control Script/FPS Input")]
public class FPSinput : MonoBehaviour {//此指令碼放在人上,不是攝像機上
    public float speed = 120.0f;
    public float g = -9.8f;
    private CharacterController _charController;
    // Use this for initialization
    void Start () {
         _charController = GetComponent<CharacterController>();
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetKeyDown(KeyCode.X)) { speed += 10.0f; }
        float deltaX = Input.GetAxis("Horizontal") * speed;
        float deltaZ = Input.GetAxis("Vertical") * speed;
        Vector3 move = new Vector3(deltaX, 0, deltaZ);
        move = Vector3.ClampMagnitude(move, speed);//限制行動
        move.y = g;
        if (Input.GetKeyDown(KeyCode.Space)) {
            if(_charController.isGrounded)
            {
                move.y = 0;
                move.y -= g * 52.0f;
            }
            //rigidbody.AddForce(Vector3.up * 5.0f);
            // transform.Translate(new Vector3(transform.position.x, transform.position.y+5.0f, transform.position.z));
        }
        //有碰撞檢測
        move = transform.TransformDirection(move);//本地轉全域性變數
        _charController.Move(move* Time.deltaTime);//增量移動
       // transform.Translate(deltaX,0,deltaZ);// 無碰撞檢測
	}
}
配合Mouselook.cs