unity3d - 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);
}
}
解决方案
我的想法不是使用任何方法,例如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();
)
}
推荐阅读
- kubernetes - 为我的服务(kubernetes、nginx-ingress、letsencrypt、cert-manager)配置 https 的正确方法是什么?
- java - 我们如何获得左右子数组和相同的数组的索引‽
- php - 在没有 WAMP 或 XAMPP 的 IIS 上托管 PHP 应用程序
- google-drive-api - 如何在 Jupyter Notebooks 上使用 gDrive?
- unity3d - c# - 如何在x,y,z中旋转面对gameobect的quaterion
- python - 无法通过 Galvanize 文本编辑器运行代码
- office-js - 我可以为 OneMac for Mac 开发基于 OneNote JS 的加载项吗?
- python - 如何解决 python 中的 404 Flask 错误?
- node.js - 带参数的快速路线
- r - 修改函数以查找每行连续运行的数字的最大长度