unity 2D游戏碰撞道具增加气血效果&受伤掉血效果

代码并不高效,仅以实现效果为目的.

被攻击时调用(需要传入HP预制件父级对象)

 1  //受到伤害时,掉血
 2     public void OnHurt(Transform HP)
 3     {
 4         print("触碰到了怪物...");
 5         //遍历父级对象
 6         for (int i = HP.childCount - 1; i >= 0; i--)
 7         {
 8             //创建临时变量T,假设是最后一个元素
 9             int t = HP.childCount - 1;
10             //比对一致时,表示找到了一样的子级
11             if (i == t)
12             {
13                 //说明还有血
14                 if (i > 0)
15                 {
16                     print(i);
17                     print("还有血...");
18                     //删除最后一个对象(小红心)
19                     Destroy(HP.GetChild(t).gameObject);
20                 }
21                 else
22                 {
23                     print("没血了");
24                     //没血了,重新加载当前场景
25                     ReStart();
26                 }
27             }
28         }
29     }

 

触碰加血道具对象时调用(需要传入HP预制件父级对象)

 1 //触碰加血道具时,加血
 2     public void AddHp(Transform hp)
 3     {
 4         if (hp.childCount == 10)//满血限制
 5         {
 6             print("满血了");
 7             return;
 8         }
 9 
10         //临时变量,存储HP父级最后一个子级的坐标x
11         for (int i = hp.childCount - 1; i > 0; i--)
12         {
13             //创建临时变量,用于存储最后一个元素;
14             var t = hp.childCount - 1;
15             //相等时,表示找到最后一个元素
16             if (i == t)
17             {
18                 //获取最后一个元素的x,Y坐标
19                 var posX = hp.GetChild(i).gameObject.transform.position.x;
20                 var posY = hp.GetChild(i).gameObject.transform.position.y;
21                 //Instantiate(要生成的对象预制件,坐标,旋转,父级)x轴偏移值,可以自行更改
22                 Instantiate(hp_yzj, new Vector3(posX += 39f, posY, 1), Quaternion.identity, hp);
23             }
24         } 
25     }

 

效果

posted @ 2021-05-15 21:11  伊凡晴天  阅读(1227)  评论(0编辑  收藏  举报