- Home /
2 objects collide, need to destroy one
Hello, I have 2 objects with rigidbodies attached. One is a character controller (the character I'm moving) and the other is an enemy NPC. When my character collides with this enemy NPC I want him to destroy the NPC. I couldn't figure out how to do it with OnCollisionEnter so I am trying OnTriggerEnter and I created a capsule collider, attached it to the enemy NPC with "is trigger" checked. Any ideas? Everything I read shows this should be pretty simple but I can't seem to figure it out. The following script is attached to the enemy NPC:
function OnTriggerEnter(hit : Collider){
if (hit.gameObject.tag == "Player2") { Destroy (gameObject); } }
Can you tell us more? For example, is your character actually being moved by the rigidbody, or is it just slaved to a CharacterController component? What you're trying to do should work, so presumably there's something else happening here.
the character is being moved by a character controller component.
Well, that's the problem. CharacterControllers hate physics, and ignore it whenever they can.
so i basically need to remove the character controller, put on a sphere collider and re-write all of my scripting for my character's movement? There has got to be a better way...
Answer by IronFurball · Jan 22, 2012 at 11:36 PM
if im right(not sure) there are a couple of things wrong,or maybe u didnt tell us yet :P
the player(the object that moves) needs to have both a rigidbody and a collider and i think the script needs to be attached to him instead of the npc, try that and let us know if it works.
Answer by aldonaletto · Jan 22, 2012 at 11:44 PM
If the capsule collider is a component added to the NPC, it should work, but if it's an object childed to the NPC, only the trigger will be destroyed (you should use Destroy(transform.parent.gameObject) in this case).
Another point: the collision character->trigger works fine, but trigger->character is detected only if the trigger has a rigidbody (even a kinematic one): if the trigger is childed to the NPC, make sure it has a kinematic rigidbody (a non-kinematic rigidbody may be moved or rotated by AddForce or AddTorque).
i'm going to need to mess around with this more... the npc moves through waypoints so I'm not sure if this is affecting something. The capsule collider (trigger) is a component added to the NPC, not an object childed to the NPC.
if the NPC is a CharacterController, move it with $$anonymous$$ove or Simple$$anonymous$$ove - just modifying its position directly or via Translate may frustrate the collision detection.
Just like to add that CharacterControllers have their own collision method: see CharacterController.OnControllerColliderHit
thank you for the tip... I figured that part out as well. I got it working finally!
Your answer
Follow this Question
Related Questions
Destroy object 1 if player walks into object 2 1 Answer
Colliding two GameObjects 1 Answer
Keep doing something while colliding 1 Answer