- Home /
How to tell if a 2D object is in a certain area
I'm creating a game field and trying to figure out how to tell if a 2D object is on a certain side of the field. How can I go about doing this?,I'm creating a field and I am trying to figure out how to create a bool returned of some kind if the 2D object is on one side of the field. How can I go about doing this?
hi, one way is to add a separate collider to each field
Answer by theInsomniacGameMaker · Sep 23, 2018 at 06:42 AM
This is what I understand from your question. You want to divide your game field into two parts and you want to know if a game object is in a certain section. I can think of two ways to approach this problem. One using the position of the game object and another using Trigger Colliders.
I think the Trigger Collider is the best way, it will save you a lot of lines of code.
Make two empty game object and add two BoxCollider2D components to both of the game objects. Name them "Section 1" and "Section 2". Also for the BoxCollider2D component, check isTrigger checkbox.
Now to the object that you want to detect the side of the field. Attach a script to it if it doesn't have a script attached to it. In the script add two bools.
bool isInSection1, isInSection2;
After that add a new function called OnTriggerEnter2D. Below is how your logic would look like.
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Section 1")
{
isInSection1 = true;
isInSection2 = false;
}
else if (collision.gameObject.name=="Section 2")
{
isInSection1 = false;
isInSection2 = true;
}
}
When the isInSection1 is true, it is in the first section and obviously the same holds true for the isInSection2.
Also, remember the object that you are detecting for should have a Rigidbody2D component and also some sort of 2D collider.
You can adjust the BoxCollider2D component of the empty game object to make the sections as big or as small you would like.
Read about the BoxCollider2D in the documentation and the OnTriggerEnter2D function in Scripting reference.
Answer by KyleLeitao · Sep 23, 2018 at 06:45 AM
I figured out the problem. It was the ignore raycast. I couldn't use the mouse because of it.
Your answer
Follow this Question
Related Questions
Why is my character not colliding with other objects. 3 Answers
Player getting stuck between grounds 0 Answers
2D Detect collisions of a 2D block only on left/right (not top/bottom) 0 Answers
Tilemap collider doesn't appear 1 Answer
How can I make sure triggers or collisions are never skipped even for high speeds? 2 Answers