using System.Collections; using System.Collections.Generic; using UnityEngine; public class cs01 : MonoBehaviour { Vector3 vel; int num = 0; // 監測鍵盤,必須在update()裡面監測 void Update() { //完美移動演算法的5步驟: //(2)判斷鍵盤ADWS則移動➜設定vel.x = ....,vel.y = ....(可以用2種方式:Input.GetAxis, Input.GetKeyDown) vel.x = Input.GetAxis("Horizontal") * 9; vel.z = Input.GetAxis("Vertical") * 9; //(3)如何鍵盤停止則移動停止➜判別鍵盤放開Input.GetKeyUp則vel.x = 0.... if (Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D)) { vel.x = 0; } if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S)) { vel.z = 0; } //(4)如何能夠有向上跳躍的力學效果➜space鍵盤則使用addforce(但沒有設定vel.y) //按空白鍵次數num,若num=0或1,就可以向上跳,num=2,就不可以跳 if (Input.GetKeyDown(KeyCode.Space) && num < 2) { this.gameObject.GetComponent().AddForce(Vector3.up * 390); num += 1; } //if (this.gameObject.GetComponent().velocity.y == 0) //{ // num = 0; //} //(5)注意:要設定vel.y(= this.gameObject.GetComponent().velocity.y vel.y = this.gameObject.GetComponent().velocity.y; //(1)如何能夠連續運動➜在update內設定幀動畫移動公式➜剛體.velocity=vel,才能控制鍵盤放開讓速度 = 0)(不能使用transform.TransLate, 剛體.AddForce) this.gameObject.GetComponent().velocity = vel; //輸出變數有2種方法: //Debug.Log(this.gameObject.transform.position.y); //print(this.gameObject.transform.position.y); //print(vel); } //private void OnTriggerEnter(Collider other) //{ // print("OnTriggerEnter"); // num = 0; //} //若發生碰撞collision,則碰撞次數num歸零=0 private void OnCollisionEnter(Collision collision) { print("OnCollisionEnter"); num = 0; } }