- Home /
OnTriggerEnter - check if collider is child
I'm making a 3d version of the classic game Asteroids. The player can fire torpedos at asteroids/enemy ships. When the player clicks the mouse button a torpedo is fired out from the player's ships location. The torpedo has a trigger collider on it which causes it to explode OnTriggerEnter. Torpedo is the child of the player ship. Currently, I have it working so that the torpedo checks if the collider that enters the trigger is the torpedo's parent, if not explode.
void OnTriggerEnter(Collider other)
{
if (other != parentColl)
{
Instantiate(explosion, transform.position, transform.rotation);
Destroy(this.gameObject);
}
}
what I need to be able to do is on the ship check if the collider entering the ships trigger is its child, to avoid damaging the player. That way, when the player's ship collides with an asteroid/enemy ship/enemy torpedo, they take damage. Currently, firing a torpedo causes damage to player without exploding the torpedo. How can I check if the collider passed into OnTriggerEnter is a child of the player ship?
instantiation of torpedo (in script attached to player ship):
if (Input.GetButtonUp("Fire1"))
{
Instantiate(torpedo, this.transform.position, this.transform.rotation, this.transform);
}
Would there be a way to set the instantiated torpedo's tag to something like PlayerTorpedo within the script that instantiates it? That way I could check tag and go from there. I tried doing this by instantiating within a variable, but I can't alter the tag because the variable is apparently an object, rather than a gameObject. Which confuses me because I've seen similar things done elsewhere, but usually with java.
Though I suppose I could set up two torpedo prefabs with nothing different other than tag.
Setting up to separate prefabs and checking if tag = PlayerTorpedo has worked, though i'd still like to know if there is a better/different way.
Why is the torpedo a child of the object that spawned it? That doesn't sound right at all.
Unless I'm badly mistaken, child colliders shouldn't fire collision events with their parents in the first place. This is what allows people to build complex shapes like humanoid shapes with hitboxes on limbs, etc.
So there shouldn't be a problem right now - the problem you're describing should come into play when you make the torpedo independent of the player like you're (almost always) supposed to.
Anyway, when that happens, you'll want to look into different layers, or simply responding to the projectile's "who fired me" reference so that if it's YOU, you don't set off the explosion.
Answer by AurimasBlazulionis · Dec 06, 2016 at 08:56 PM
Assuming the ships are the root transforms you can check it using something like if (other.transform.root != parentRoot)
. You do not really need to check the colliders, but instead, transforms.