6
\$\begingroup\$

I have a player that shoots in the direction that it is facing. However, the shot that is created when I click, also destroys the player (example). How would I make the shot ignore collision with the player? Or better yet, how to make a shot destroy anything it touches and destroy itself without affecting the player?

This is the code that controls collisions:

function OnTriggerEnter (col : Collider) {
    Destroy(col.gameObject);
}

The shot is a trigger, but the player isn't. Not sure if this changes anything in this case.

\$\endgroup\$
10
\$\begingroup\$

There are a lot of ways to ensure that.

The best approach is to use the "Layer Collision Matrix". To keep things organized, you could create a Bullets, Enemies and a Player Layer. Then go to Edit > Project Settings > Physics and you'll see the collision matrix.

Unity Layer Collision Matrix

You can check all the layer-pairs that should report collisions there. In the screenshot you can see that Bullets will only collide with Enemies and Enemies also collide with the Player. Then all that's left to do is assign the matching layers to your GameObjects or Prefabs.

Using the collision matrix is the best approach, because it directly affects the physics simulation (non-colliding layers don't have to be checked for collisions at all) which is the most performant solution to your problem.

Another approach (or you could also combine the two) is to implement OnCollisionEnter or OnTriggerEnter on the Enemies and Players, and not the Bullet. Then you're free to implement different behavior for each entity and also report scores or perform other tasks.

Bullets could also use

col.gameObject.SendMessage("HitByBullet", null,
    SendMessageOptions.DontRequireReceiver);

instead of your current Destroy(col.gameObject). Then you can implement a HitByBullet method in your Enemy Script and destroy the object there, play a sound effect etc.

\$\endgroup\$
5
\$\begingroup\$

You can use Physics.IgnoreCollision and make your projectile ignore your player: http://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html

Or, you could specify and use 3 different layers: one for your player, one for your projectile, and one for your enemies. Then if you go Edit > Project Settings > Physics, you can adjust the collision matrix to ensure that your projectile and player layers don't collide with each other.

Or, within your OnTriggerEnter function, you could check to see if the col.gameObject.name matches your player's name, or check col.gameObject.tag, or col.gameObject.GetComponent(Foo) to see if the collider contains a component that only your player uses.

Few different ways!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.