Unity3d:我的击退脚本不起作用

本文关键字:脚本 不起作用 我的 Unity3d | 更新日期: 2023-09-27 18:27:28

我的代码不起作用。当我与一个物体碰撞时,没有发生任何事情,我确保我的物体盒碰撞器被选中为isTrigger,我还增加了爆炸强度。我做错了什么有人能帮忙吗?

public class Knockback : MonoBehaviour 
{
    public float explosionStrength = 10.0f;
    void OnTriggerEnter2D (Collider2D target_)
    {
        Vector3 forceVec = -target_.GetComponent<Rigidbody2D>().velocity.normalized * explosionStrength;
        target_.GetComponent<Rigidbody2D>().AddForce(forceVec,ForceMode2D.Force);
    }
}

Unity3d:我的击退脚本不起作用

您正在混合unity3d代码和unity2d代码。如果您在unity3d中,则您的代码可能需要更改为。。。

public class Knockback : MonoBehaviour {
    public float explosionStrength = 10.0f;
    void OnTriggerEnter (Collider target_){
    Vector3 forceVec = -target_.GetComponent<Rigidbody> ().velocity.normalized * explosionStrength;
        target_.GetComponent<Rigidbody>().AddForce(forceVec,ForceMode.Force);
    }
}

如果你在2d中,你的代码可能需要更改为这个

    public class Knockback : MonoBehaviour {
    public float explosionStrength = 10.0f;
    public GameObject player;
    void OnTriggerEnter2D (Collider2D target_){
         Vector2 forceVec = new Vector2 (-target_.GetComponent<Rigidbody2D> ().velocity.normalized.x * explosionStrength, -target_.GetComponent<Rigidbody2D> ().velocity.normalized.y * explosionStrength);
    target_.GetComponent<Rigidbody2D>().AddForce(forceVec,ForceMode2D.Force);
}
}

我已经测试了2d代码,它运行得很好。只要确保你把它放在物体上爆炸,而不是放在玩家身上。