// prg6-12 顯示蘋果次數於ui using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class PlayerController : MonoBehaviour { Rigidbody2D rigi2D; Animator animator; float jumpForce = 680.0f; float walkForce = 30.0f; float maxWalkSpeed = 2.0f; float threshold = 0.2f; GameObject Apple; int Apple_eats = 0; // Start is called before the first frame update void Start() { this.rigi2D = GetComponent(); this.animator = GetComponent(); Apple = GameObject.Find("Apple_text"); } // Update is called once per frame void Update() { //Jump //if(Input.GetMouseButtonDown(0) && this.rigi2D.velocity.y == 0) { // this.animator.SetTrigger("JumpTrigger"); // this.rigi2D.AddForce(transform.up*this.jumpForce); //} if(Input.GetKeyDown(KeyCode.Space) && this.rigi2D.velocity.y ==0) { this.animator.SetTrigger("JumpTrigger"); this.rigi2D.AddForce(transform.up * this.jumpForce); } // Left Right Move int key = 0; //手機傾斜移動 //if(Input.acceleration.x > this.threshold) key = 1; //if(Input.acceleration.x < this.threshold) key = -1; //左右鍵切換面向 if(Input.GetKey(KeyCode.RightArrow)) key = 1; if(Input.GetKey(KeyCode.LeftArrow)) key = -1; float speedx = Mathf.Abs(this.rigi2D.velocity.x); if(speedx < this.maxWalkSpeed) { this.rigi2D.AddForce(transform.right * key * this.walkForce); } //圖片翻轉 if (key !=0) { transform.localScale = new Vector3(key, 1, 1); } //依照遊戲角色的速度改變動畫的速度 if(this.rigi2D.velocity.y == 0) { this.animator.speed = speedx / 2.0f; } else { this.animator.speed = 1.0f; } if(transform.position.y < -10) { SceneManager.LoadScene("GameScene"); } } void OnTriggerEnter2D(Collider2D other) { //Debug.Log("End"); Debug.Log(gameObject.tag + " entered Trigger tagged " + other.gameObject.tag); if (other.gameObject.tag == "Apples") { Debug.Log(other.gameObject.tag); Destroy(other.gameObject); Apple_eats += 1; Apple.GetComponent().text = "Apple :"+Apple_eats.ToString("D2") + "蘋果"; } if (other.gameObject.tag == "Pigs") { Debug.Log(other.gameObject.tag); Destroy(other.gameObject); } if (other.gameObject.name == "flag") { Debug.Log("Finish !"); SceneManager.LoadScene("ClearScene"); } } }