Unity 2D横版射击项目:投射物无法与敌人碰撞问题求助
Hey there! Let's break down why your projectile might be passing through enemies even though you followed the tutorial closely. I've run into similar tiny mishaps when starting out with Unity 2D collisions, so here are some common fixes to check:
Check the Layer Collision Matrix
Unity’s Physics 2D settings might be blocking collisions between your projectile and enemy layers. Head toEdit > Project Settings > Physics 2Dand look at the Layer Collision Matrix. Make sure the layers assigned to your projectile and enemy are set to collide with each other—it’s super easy to accidentally uncheck a box here!Verify Enemy Collider and Tag Details
- Double-check that your enemy has a Collider 2D component (e.g., BoxCollider2D, CircleCollider2D) attached, and that its
Is Triggeroption is disabled (since you’re usingOnCollisionEnter2D, not trigger-based detection). - Confirm the enemy’s tag is exactly
"Collision"—Unity tags are case-sensitive! If the tutorial uses a different tag (like"Enemy"), that’s a quick fix.
- Double-check that your enemy has a Collider 2D component (e.g., BoxCollider2D, CircleCollider2D) attached, and that its
Validate Projectile Collider Settings
Ensure your projectile’s Collider 2D is also set toIs Trigger = false, and that its size/shape properly covers the projectile sprite. A tiny or offset collider might miss the enemy entirely, even if it looks like they’re hitting.Deep Dive into Rigidbody 2D Config
Even if you confirmed the Rigidbody 2D exists, check these settings:- Set
Body Typeto Dynamic (dynamic bodies interact correctly with other colliders in 2D physics). - Enable Continuous Collision Detection (set to
ContinuousorContinuous Dynamic) if your projectile moves very fast. Fast objects can "tunnel" through colliders without CCD enabled. - Make sure
Gravity Scaleis set as per the tutorial (usually 0 for straight-firing projectiles).
- Set
Add Debug Logs to Test Collision Triggers
Modify yourOnCollisionEnter2Dmethod to log collisions, so you can see if the event is even firing:void OnCollisionEnter2D (Collision2D tempCollision) { Debug.Log("Collided with: " + tempCollision.gameObject.name + " | Tag: " + tempCollision.gameObject.tag); if (tempCollision.gameObject.tag == "Collision") { spawnParticles(tempCollision.transform.position); Destroy(tempCollision.gameObject); Destroy(gameObject); // Don't forget to destroy the projectile too! } }Run the game and check the Console window. If no logs appear when the projectile hits the enemy, the collision isn’t being registered at all—pointing back to layer, collider, or tag issues.
Check Destruction Order
In your current code, you destroy the enemy but not the projectile. While this might not cause the pass-through issue, addingDestroy(gameObject);inside the collision block ensures the projectile doesn’t keep moving through other objects after hitting the first enemy.
内容的提问来源于stack exchange,提问作者PremiumOxygen




