2015-12-19 67 views
0

我的代碼無法運行。當我碰撞一個沒有真正發生的物體時,我確定我的物體箱對撞機被檢測到isTrigger,並且我也增加了爆炸強度。我做錯了什麼人都可以幫忙?Unity3d:我的回擊腳本不工作

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); 
    } 
} 
+0

你在3d還是2D? – Mindstormer

回答

0

如果你是在統一的3D那麼你的代碼可能需要改變這個你混合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代碼,它工作正常。只要確保你把它放在物體上而不是玩家爆炸。