- Home /
Find a gameobject with the same position
I want to check if another gameobject has the same position!
public void update()
{
if (GameObject.FindGameObjectWithTag("wall").transform.localPosition == gameObject.transform.localPosition)
{
//something happens
}
}
Answer by M-G-Production · Aug 23, 2017 at 04:12 PM
First you should consider storing that 'wall' into a local variable to increase performance.
Then you should use position instead of localPosition (position is the real world position, localPosition is the position as child relative to its parent.)
Finally, I'd say that the chance of the wall being exactly at the same place could be pretty hard to validate (depending on the way you are programming your game)... You could create a method that could compare the values with a certain distance...
Adjust your script like this:
GameObject theWall;
public void update()
{
if (theWall == null)
theWall = GameObject.FindGameObjectWithTag("wall");
if (AreNear(theWall.transform.position, gameObject.transform.position, 0.1f))
{
//Something Happens
}
}
//This method detects if the object are close depending on minDistance value
bool AreNear(Vector3 obj1, Vector3 obj2, float minDistance = 0)
{
return ((obj1.x < obj2.x + minDistance && obj1.x > obj2.x - minDistance) &&
(obj1.y < obj2.y + minDistance && obj1.y > obj2.y - minDistance) &&
(obj1.z < obj2.z + minDistance && obj1.z > obj2.z - minDistance));
}
Update need to start with an uppercase letter. $$anonymous$$aybe the code in question was just pseudo code, but when writing answers they should be correct.
Answer by spraw · Aug 23, 2017 at 05:21 PM
bool IsInDistance(Transform a, Transform b, float maxDistance)
{
return Vector3.Distance(a.position, b.position) <= maxDistance;
}
Your answer
Follow this Question
Related Questions
Locking gameobject to rotating floor 0 Answers
C# round transform.position floats to .5 2 Answers
stop object(door) translation 0 Answers