I’m trying to get the colliders working for a platformer. I have a collider on the enemy, and a collider on the player.
I’m going off of a tutorial I did previously, but I’m trying to understand how the two colliders interact.
I want the player to jump on the head of the enemy to kill it, but if the enemy touches the side of the player, it should kill the player.
So, I will have the collider at the feet of the player, so I can have a trigger there to see if I’m colliding with the enemy, but wouldn’t that also trigger the enemy’s onCollision/onTrigger to kill the player? Do I need to have a separate collider just on the head of the enemy to prevent a head-jump from killing the player? Will the onCollisions be executed in a guaranteed order that I could take advantage of here?
On a related question, is it possible for a single object to have two colliders that can both be triggers and have different behaviors? Is it possible somehow to see which collider was involved in a collision?
You can have multiple colliders. The trick is to make them children of the Rigidbody. That way they still work for physics, but you can check for collision individually.
Once you have the children objects set up with their individual colliders/triggers you can then have EACH CHILD OBJECT call a function once they are triggered.
For example, the collider that’s positioned at the head is attached to a ‘headtrigger’ object of the player. This ‘headtrigger’ object has a script that contains “OnTriggerEnter(collider other)”. When the head trigger is tripped, it calls the headtriggers’ script, which in turn has a call to a public function on the main playerscript.
Does this make sense… or have I just muddied the waters? lol.
Here’s and example in code, starting in the headtrigger script:
//(inside the headtrigger class)
public void OnTriggerEnter(collider other)
{
if(other.CompareTag("Enemy"))
{
playerMainScript.LandedOnHead(other.gameObject);
}
}
Then in your playerMainScript you could have this:
//(inside the mainplayer script)
public void LandedOnHead(GameObject squashedEnemy)
{
// if you need to get any info from the enemy use
// squashedEnemy.GetComponenet<EnemyScript>();
Destroy(squashedEnemy);
score++;
}
P.S. I haven’t been doing this wrong, so be prepared for an update on this from other users.
Okay, so just to make sure I understand… You guys are saying to make child objects of my main player object, and have each of those have separate colliders, which could then each have their on OnTriggerEnter functions. That makes sense.
BoredMormon: this is what you are suggesting as well, right? Or are you suggesting something that doesn’t require separate gameobjects? (just making sure that I understand).
There are other more complex variants, but they are all based on the basic principle of having multiple colliders on separate GameObjects that are children of your main object.