Box.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class Box : MonoBehaviour
  5. {
  6. [System.NonSerialized] public int bombDivideCount = 3;
  7. float boxWidth;
  8. float parentHeight;
  9. void Start()
  10. {
  11. boxWidth = (transform as RectTransform).rect.width;
  12. parentHeight = (transform.parent as RectTransform).rect.height;
  13. GetComponent<BoxCollider2D>().size = Vector2.one * boxWidth;
  14. }
  15. // Update is called once per frame
  16. void Update()
  17. {
  18. transform.localPosition += Vector3.down * GameMode.boxDownSpeed * Time.deltaTime;
  19. if (transform.localPosition.y < -parentHeight / 2 + boxWidth / 2) Bomb();
  20. }
  21. bool hasBomb = false;
  22. public void Bomb()
  23. {
  24. if (hasBomb) return;
  25. hasBomb = true;
  26. RectTransform boxRTF = transform as RectTransform;
  27. float boxWidth = boxRTF.rect.width;
  28. //左下角开始
  29. Vector2 childStartPoint = new Vector2();
  30. childStartPoint.x = childStartPoint.y = -(boxWidth/2)+(boxWidth/bombDivideCount)/2;
  31. float childWidth = boxWidth / bombDivideCount;
  32. GameObject childPrefab = transform.GetChild(0).gameObject;
  33. for (int x = 0; x < bombDivideCount; x++)
  34. {
  35. for (int y = 0; y < bombDivideCount; y++)
  36. {
  37. Vector2 pos = new Vector2(childStartPoint.x + childWidth * x, childStartPoint.y + childWidth * y);
  38. RectTransform childRTF = Instantiate(childPrefab, boxRTF).transform as RectTransform;
  39. childRTF.localPosition = pos;
  40. childRTF.sizeDelta = new Vector2(childWidth, childWidth);
  41. childRTF.gameObject.SetActive(true);
  42. BombChild bombChild = childRTF.gameObject.AddComponent<BombChild>();
  43. Vector2 pointer = (bombChild.transform.position - transform.position).normalized;
  44. if (pointer.Equals(Vector2.zero))
  45. {
  46. Destroy(childRTF.gameObject);
  47. continue;
  48. }
  49. bombChild.velocity = pointer * Random.Range(600, 800);
  50. childRTF.gameObject.transform.SetParent(transform.parent);
  51. }
  52. }
  53. Destroy(gameObject);
  54. }
  55. }