当敌人被击中时,如何用力量将其击退?



我在Unity中制作简单的战斗系统,我已经添加了伤害系统,但我想升级它,并在敌人受到伤害时将其击退。我已经做了一些尝试,但没有工作正确。这是我的一小段代码。谢谢你的建议。

public class EnemyTakeDmg : MonoBehaviour
{
public int health = 8;
private Rigidbody myBody;
public float knockBackForce = 5f;

public event System.Action OnDeath;
private void Start()
{
myBody = GetComponent<Rigidbody>();
}
public void TakeDamage(int damage)
{
health -= damage; // TAKING DAMAGE
// PUSHING ENEMY BACK ???

if(health <= 0)
{
Die();
}
}

public void Die()
{
if(OnDeath != null)
{
OnDeath();
}
Destroy(gameObject);
}

}

我建议以某种方式获取拍摄对象的引用。这是计算回退方向所必需的。

之后,就很容易了!

public void TakeDamage(int damage, Transform shooter)
{
//Take damage
health -= damage;
//Knockback
Vector3 direction = (transform.position - shooter.position).normalized;
myBody.AddForce(direction * knockBackForce);
}

方向可能相反,因此您可能需要切换shooter.positiontransform.position

最新更新