// prg6-12 顯示蘋果次數於ui using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using TMPro; public class PlayerController : MonoBehaviour { // Start is called before the first frame update public TextMeshProUGUI textMeshProUGUI; Rigidbody2D rigid2D; Animator animator; float jumpForce = 680.0f; float walkForce = 10.0f; float maxWalkSpeed = 2.0f; float threshold = 0.2f; GameObject director; GameObject Apple; GameObject Pig; int Apple_eats = 0; int Pig_eats = 0; void Start() { this.rigid2D = GetComponent(); this.animator = GetComponent(); Apple = GameObject.Find("Apple_text"); Pig = GameObject.Find("Pig_text"); director = GameObject.Find("GameDirector"); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space) && this.rigid2D.velocity.y == 0) { this.animator.SetTrigger("JumpTrigger"); this.rigid2D.AddForce(transform.up * this.jumpForce); } if (Input.GetMouseButtonDown(0) && this.rigid2D.velocity.y == 0) { this.animator.SetTrigger("JumpTrigger"); this.rigid2D.AddForce(transform.up * this.jumpForce); } int key = 0; if(Input.GetKey(KeyCode.RightArrow)) key = 1; if(Input.GetKey(KeyCode.LeftArrow)) key = -1; if(Input.acceleration.x > this.threshold) key = 1; if(Input.acceleration.x < -this.threshold) key = -1; float speedx = Mathf.Abs(this.rigid2D.velocity.x); if(speedx < this.maxWalkSpeed) { this.rigid2D.AddForce(transform.right * key * walkForce); } if(key != 0) { transform.localScale = new Vector3(key, 1, 1); } if(this.rigid2D.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) { if (other.gameObject.name == "flag") { Debug.Log("flag!"); SceneManager.LoadScene("ClearScene"); } if (other.gameObject.tag == "Apple") { Debug.Log(other.gameObject); Destroy(other.gameObject); director.GetComponent().IncreaseHp(); Apple_eats +=1; Apple.GetComponent().text = "Apple : "+Apple_eats.ToString("D2"); } if (other.gameObject.tag == "Pigs") { Debug.Log(other.gameObject); Destroy(other.gameObject); director.GetComponent().DecreaseHp(); Pig_eats +=1; Pig.GetComponent().text = "Pig : "+Pig_eats.ToString("D2"); } } //void OnCollisonEnter2D(Collider2D coll) { // Debug.Log("Collision Detection!"); // print("FINISH!"); //} }