using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class cs01 : MonoBehaviour { float v1 = 3f, v2 = 1; float rx, ry, rz = 0; int score = 0; public AudioClip au1; public Text t1; Vector3 vel; void Update() { //移動5步驟 //1.vel.x, vel.y vel.x = Input.GetAxis("Horizontal") * v1; vel.z = Input.GetAxis("Vertical") * v1; //2.放開A,D,W,S if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) { vel.x = 0; } if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) { vel.z = 0; } //3.space-jump-addforce if (Input.GetKeyDown(KeyCode.Space)) { this.gameObject.GetComponent().AddForce(Vector3.up * 300); } //4.vel.y vel.y = this.gameObject.GetComponent().velocity.y; //5.物件坐標視角移動(達成space.self效果,以物件座標來前進) //5-1步驟1:計算局部坐標的合成向量 //前進合成向量 movePos = 向量(x,y) = x向量 * 移動值 + y向量 * 移動值 // (錯誤) = Vector3.right* vel.x + Vector3.forward * vel.z // (正確) = transform.right * vel.x + transform.forward * vel.z; //Vector3 movePos = Vector3.right* vel.x + Vector3.forward * vel.z; Vector3 movePos = transform.right * vel.x + transform.forward * vel.z; //兩種單位向量:局部坐標向量 / 世界坐標向量 //(1)局部(自身)座標,單位向量,只有座標軸的正方向沒有負方向 //Transform.forward 向前 //Transform.right 向右 //Transform.up 向上 //(2)世界座標,單位向量 //Vector3.forward 向前 //Vector3.back 向後 //Vector3.left 向左 //Vector3.right 向右 //5-2步驟2:顯示局部坐標,(vel.x, vel.y, vel.z) vel.x = movePos.x; vel.z = movePos.z; //5-3步驟3:局部坐標設定剛體移動的velocity,(vel.x, vel.y, vel.z) this.gameObject.GetComponent().velocity = vel; //旋轉 rx = 0; ry = Input.GetAxis("Rotate") * v2; rz = 0; this.transform.Rotate(rx, ry, rz, Space.Self); } //真實物體碰撞的物理效果:Collision //缺點:碰撞後,球會被撞而旋轉 private void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "Cylinder1" || collision.gameObject.name == "Cylinder2") { //刪除被碰撞的物件 Destroy(collision.gameObject); //播放音效 this.gameObject.GetComponent().Play(); //顯示分數 score += 5; t1.text = "分數:" + score.ToString(); //若是100分,顯示過關 if (score == 100) { this.gameObject.GetComponent().clip = au1; this.gameObject.GetComponent().Play(); t1.text = "恭喜,過關"; } } } //只是感應,而不真實碰撞:Trigger //優點:接觸後,球不會被撞而旋轉 private void OnTriggerEnter(Collider other) { if (other.gameObject.name == "Cylinder3" || other.gameObject.name == "Cylinder4" || other.gameObject.name == "Cylinder5") { //刪除被碰撞的物件 Destroy(other.gameObject); //播放音效 this.gameObject.GetComponent().Play(); //顯示分數 score += 30; t1.text = "分數:" + score.ToString(); //若是100分,顯示過關 if (score == 100) { this.gameObject.GetComponent().clip = au1; this.gameObject.GetComponent().Play(); t1.text = "恭喜,過關"; } } } }