How to check if a GameObject is inside and area
Hello Guys, first of all, sorry if my Eglish is not the best, i'm not a native speaker.
I'm trying to detect if a gameObject is inside an area of the world. I have made an imaginary square to use it as the limits of the area.
I made an "If" to check if the transform.position.x,y,x of the gameObject and then I compared them with the limits of the area:
float ballx = GameObject.Find("Ball1").transform.position.x;
float bally = GameObject.Find("Ball1").transform.position.y;
float ballz = GameObject.Find("Ball1").transform.position.z;
if (bally > 0.3f && bally < 0f && ballz > 1.3f && ballz > 0.6f && ballx > -1.32f && ballx > -1.7f) {
Debug.Log("out")
}
I have already tried to create an empty with a Collider and working with OnCollisionExit and OnTriggerExit but i couldn't make it. I know it may not be the best way to do something like this, but i think its the one that i have closer
I have also checked the similar questions
Thank you
maybe you should search for OnTriggerEnter. Waay to useful.
OFF TOPIC also try to avoid using Find(). It slows down your game too much. you can use static instances or drag drop them in the inspector for better performance.
Answer by Hellium · Jan 08, 2019 at 12:38 PM
Vector3 ballPosition = GameObject.Find("Ball1").transform.position ;
Vector3 minPosition = new Vector3( 0, 0.6f, -1.7f );
Vector3 maxPosition = new Vector3( 0.3f, 1.3f, -1.32f );
bool isIn = true;
for( int i = 0 ; i < 3 && isIn ; ++i )
{
if( ballPosition[i] < minPosition[i] || ballPosition[i] > maxPosition[i] )
isIn = false ;
}
if( isIn )
Debug.Log( "The ball is inside the area" ) ;
else
Debug.Log( "The ball is outside of the area" ) ;
Or, closer solution to yours
Vector3 ballPosition = GameObject.Find("Ball1").transform.position ;
Vector3 minPosition = new Vector3( 0, 0.6f, -1.7f );
Vector3 maxPosition = new Vector3( 0.3f, 1.3f, -1.32f );
if(
ballPosition.x < minPosition.x || ballPosition.x > maxPosition.x ||
ballPosition.y < minPosition.y || ballPosition.y > maxPosition.y ||
ballPosition.z < minPosition.z || ballPosition.z > maxPosition.z
)
Debug.Log( "The ball is outside of the area" ) ;
else
Debug.Log( "The ball is inside the area" ) ;
Your answer
Follow this Question
Related Questions
instantiated gameobject position is not working 0 Answers
Why transform.localPosition is incorrect on mobile? 1 Answer
Make gun aim? 0 Answers
Having trouble moving a GameObject to another scene and Transform it to a different position 0 Answers
After using transform.position, gameobject resets z-axis position 1 Answer