敵人被殺,你跳到他身上,一接觸,我和敵人都受到傷害,我怎么保證只對敵人造成傷害?你需要為此使用什么?
腳本系結了敵人和玩家:
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);
}
}

uj5u.com熱心網友回復:
檢查Collision2D檔案。“參與碰撞的傳入游戲物件。” Socoll.gameObject.GetComponent<Health>();指的是傳入的物件,腳本系結了敵人和玩家,兩者都參與了碰撞。因此,當玩家與敵人發生碰撞時,雙方都會消耗健康,反之亦然。
僅將腳本附加到敵人身上,以便在玩家collisionTag碰撞時僅從他身上獲取能量。
另一方面,在if和 中發生同樣的事情else,使它無用:)
if (point2D.normal.y >= 0.5f)
{
//Destroy(enemy.gameObject);
health.takeDamage(damage);
}
else
{
health.takeDamage(damage);
}
uj5u.com熱心網友回復:
我的想法是不使用任何方法,例如takeDamage()只使用變數,這樣效率會更高。
創建一個GameManager類并將敵人和玩家的生命值放在 int 或 long 變數中,并將其值設定為最大生命值。
然后創建一個 GameManager 類本身的實體,GameManager 類中的代碼如下所示,
public static GameManager Instance = this;
public int playerHealth = 100;
public int enemyHealth = 100;
在您的 Player Prefab 創建并附加一個包含這些行的腳本,
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;
}
}
然后Update(),當玩家或敵人的健康狀況變低或等于 0 時,您可以在GameManager的方法中隨意執行該功能。
例如,
private void Update()
{
if(enemyHealth <= 0)
{
PlayerWin();
}
if(playerHealth <= 0)
{
EnemyWin();
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/347446.html
標籤:统一3d
