You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.7 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. [RequireComponent(typeof(Rigidbody2D))]
  4. public class PlayerController : MonoBehaviour {
  5. public GameObject bullet;
  6. public float speed;
  7. private int bulletDirection = -1;
  8. private Rigidbody2D rigid;
  9. private GameObject[] targets;
  10. // Use this for initialization
  11. void Start() {
  12. targets = GameObject.FindGameObjectsWithTag("Enemy");
  13. rigid = GetComponent<Rigidbody2D>();
  14. rigid.AddForce(Vector2.up * 200);
  15. }
  16. // Update is called once per frame
  17. void Update() {
  18. }
  19. public void rotatePlayer() {
  20. rigid.velocity = Vector3.zero;
  21. transform.Rotate(new Vector3(0, 0, 5f));
  22. }
  23. public void movePlayer() {
  24. rigid.AddForce(transform.right * speed,ForceMode2D.Impulse);
  25. }
  26. GameObject findClosestTarget(GameObject[] targets) {
  27. GameObject tMin = null;
  28. float minDist = Mathf.Infinity;
  29. Vector3 currentPos = transform.position;
  30. foreach (GameObject t in targets) {
  31. float dist = Vector3.Distance(t.transform.position, currentPos);
  32. if (dist < minDist) {
  33. tMin = t;
  34. minDist = dist;
  35. }
  36. }
  37. return tMin;
  38. }
  39. public void shoot() {
  40. GameObject bulletClone = (GameObject)Instantiate(bullet, transform.position + (transform.up * bulletDirection * 0.1f), transform.rotation);
  41. MissileController bulletScript = bulletClone.GetComponent<MissileController>();
  42. bulletScript.startVelocity = transform.up * bulletDirection;
  43. bulletDirection = -bulletDirection;
  44. bulletScript.target = findClosestTarget(targets);
  45. bulletScript.enabled = true;
  46. }
  47. }