首页 > 解决方案 > 2D 游戏中的健康系统

问题描述

敌人被杀,如果你跳到他身上,一接触,对我和敌人造成伤害,我怎么能确保只有敌人被处理?您需要为此使用什么?
该脚本与敌人和玩家相关联:

private void OnCollisionEnter2D(Collision2D coll)
    {
        Health health = coll.gameObject.GetComponent<Health>();

        if (coll.gameObject.CompareTag(collisionTag)) //t
        {
            foreach (ContactPoint2D point2D in coll.contacts)
            {
                if (point2D.normal.y >= 0.5f)
                {
                    //Destroy(enemy.gameObject);                    
                    health.takeDamage(damage);
                }
                else 
                {
                    health.takeDamage(damage);
                }
            }
        }
    }

我像这样尝试过,但是损坏是从一侧造成的

foreach (ContactPoint2D point2D in coll.contacts)
            {
                if (point2D.normal.y >= 0.5f)
                {
                    //Destroy(enemy.gameObject);                    
                    health.takeDamage(damage);
                    

                }
                else if (point2D.normal.x >= 0.5f)
                {
                    health.takeDamage(damage);
                }
            }

在此处输入图像描述

标签: unity3d

解决方案


我的想法不是使用任何方法,例如takeDamage()使用变量,它会更有效。

创建一个GameManager类并将敌人和玩家的生命值放在 int 或 long 变量中,并将其值设置为最大生命值。

然后创建 GameManager 类本身的实例,GameManager 类中的代码如下所示,

public static GameManager Instance = this;
public int playerHealth = 100;
public int enemyHealth = 100;

In your Player Prefab create and attach a script containing these lines,

private void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.Tag == "Enemy") //Tag your Enemy Prefab with name "Enemy".
        {
            //Now you can directly reduce the value of enemy and player health without create any reference to the GameManager class.
            
            //Whenever the player hits or come in contact with the enemy the health of player and enemy reduces by 10;

            GameManager.Instance.playerHealth -= 10; 
            GameManager.Instance.enemyHealth -= 10; 
        }
    }

You can then do the function as you wish in the Update() method of GameManager when the health of either the player or enemy's health become low or equals to 0.

For example,

private void Update()
{
    if(enemyHealth <= 0) 
    {
        PlayerWin();
    }

    if(playerHealth <= 0)
    {
        EnemyWin();
    )
}

推荐阅读