[C#][Physics2D] multiple colliders and OnCollisions on one gameobject
Greetings, I understand this has been asked but that post was old. I have a gameobject and I want it to have two colliders, (either on same GO or on a child GO) and what is more important, I want to use ONE script, that can distinguish between the two colliders. Is this possible? Regards
This is done all the time. For example you have a 2D sprite that has 3 colliders one for the head, one for the feet and one for the body.
But you need to provide more details (how will you be using each collider, what collision functions will you be using - OnCollisionEnter2D, OnTriggerEnter2D).
Any code that you have would be helpful as well.
A regular saint you are here :D I'm making a double jump trampoine. This means that I have two box collider 2d-s, one lower than the other. The reason for this is that as the player enters the first one, they can press the jump button or not. When s/he reaches the second one, the lower (second) collider adds a force upwards (say Vector2.up * jumpSpeed) or if the jump was pressed, adds double force up. I don't want to make 2 scripts for this if no necessary. my code so far, nothing complicated:
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
if (!alreadyUsed)
{
Rigidbody2D otherRB = other.gameObject.GetComponent<Rigidbody2D>();
otherRB.velocity = new Vector2(otherRB.velocity.x, 0.0f);
otherRB.AddForce(Vector2.up * CharacterController2D.jumpForce);
alreadyUsed = true;
}
}
}
void OnTriggerExit2D(Collider2D other)
{
alreadyUsed = false;
}
public class TramboulineDoubleJump : $$anonymous$$onoBehaviour
{
void OnTriggerEnder2D(Collision2D other)
{
if (other.gameObject.CompareTag("Player"))
{
}
}
}
please note that I have a parent GO that has the script (that is the upper class, named Trambouline. I just made the lower class to distinguish or what. The upper collider is on the child of the actual GO. the lower collider that actually makes the jump is on the GO itself.
I needed to reformat your comment to be more readable, but to do that I had to make it an answer first.
Uhh sorry, and I converted it back to a comment. The script is really no big deal, all in all I need just if one can have 2 OnTriggerEnter2Ds for 2 different colliders using 1 script.