前言
本节主要实现随机生成僵尸,小土豆以及一些优化
僵尸生成
新增GenerateZombies,这里先简单的,在各路随机生成僵尸
public class GenerateZombies : MonoBehaviour { public float interval; //间隔 public GameObject zombiePrefab; //僵尸预制体 private void Start() { StartCoroutine(Generate()); } private IEnumerator Generate() { int i = 0; while (true) { yield return new WaitForSeconds(interval); // 等待 int index = Random.Range(0, 5); //获取子物体 Transform pointTransform = transform.GetChild(index); GameObject go = Instantiate(zombiePrefab, pointTransform.position, Quaternion.identity); //修改排序 go.GetComponent<SpriteRenderer>().sortingOrder = i; i++; } } }
配置
效果
小土豆
配置动画
新增Plants代码,为所有植物的父类
//植物父类 public class Plants : MonoBehaviour, IInteractable { public void OnDie() { Destroy(gameObject); } }
新增WallNut代码,基础Plants
public class WallNut : Plants { Animator animator; private void Start() { animator = GetComponent<Animator>(); } private void Update() { //获取血量 float currentHealth = GetComponent<Character>().currentHealth; float maxHealth = GetComponent<Character>().maxHealth; animator.SetFloat("percentage", currentHealth / maxHealth); } }
种子完成再启动植物
修改Plants,新增isOpen变量,控制植物是否运行
public bool isOpen;//控制植物是否运行
修改对应的脚本,比如PraShooter,控制豌豆射手发射子弹,其他植物同理
IEnumerator Attack() { if(!isOpen) yield return null; while (true) { Shoot(); // 执行射击操作 yield return new WaitForSeconds(interval); // 等待interval秒 } }
修改Card
//开始拖拽 public void OnBeginDrag(PointerEventData eventData) { Debug.Log("开始拖拽"); if (progressBar.GetComponent<Image>().fillAmount != 0 || GameManager.Instance.sunSum < useSun) return; thisObject = Instantiate(prefab, transform.position, Quaternion.identity); //关闭运行 thisObject.GetComponent<Plants>().isOpen = false; //关闭碰撞 thisObject.GetComponent<Collider2D>().enabled = false; //关闭动画 thisObject.GetComponent<Animator>().enabled = false; } //拖拽结束 public void OnEndDrag(PointerEventData eventData) { Debug.Log("拖拽结束"); if (thisObject == null) return; Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector2 mousePosition2D = new Vector2(mousePosition.x, mousePosition.y); RaycastHit2D hit = Physics2D.Raycast(mousePosition2D, Vector2.zero, Mathf.Infinity, layerMask);//鼠标“点检测”射线 if (hit.collider != null && hit.collider.transform.childCount == 0) { thisObject.transform.parent = hit.transform; thisObject.transform.localPosition = Vector2.one; //开始运行 thisObject.GetComponent<Plants>().isOpen = true; //开启碰撞 thisObject.GetComponent<Collider2D>().enabled = true; //开启动画 thisObject.GetComponent<Animator>().enabled = true; thisObject = null; //重置进度 progressBar.GetComponent<Image>().fillAmount = 1; //扣除阳光 GameManager.Instance.SetSunSum(-useSun); } else { Destroy(thisObject); } }
效果
源码
源码不出意外的话我会放在最后一节