How would you check if an object is closer to the bottom side or top side of another object

In my game i am working on the enemies AI and I want in c# that whenever specific object comes within a certain distance, to move upwards if object is closer to the bottom side of the enemy and move down if the object is closer to the top of enemy.

	if (GameObject.Find("Laser(Clone)") != null)
		{
			float projectileDistance = Vector2.Distance(this.transform.position, GameObject.Find("Laser(Clone)").transform.position); 
			Debug.Log(projectileDistance);
			if(projectileDistance <=4.8)
			{
				rb.AddForce(transform.up * speed * Time.deltaTime);
			}
		}//this is attached to the enemy gameobject

So basically i want to know if there is a way of like splitting an object into the top half and bottom half and detect wether another object is closer to which side.

bump. Can someone please help

What kind of objects are we talking about? Something modelled in a 3D modeling software or cubes or what? If the objects are symmetrical and y-axis represents "height", you can just compare their y-coordinate. If object A has a greater transform.position.y than object B, then A is closer to the top of B...

I would just compare the transform.position of object a with one of the Bounds values of object b ([Bound.min][1] and [Bounds.max][2]). [1]: http://docs.unity3d.com/ScriptReference/Bounds-min.html [2]: http://docs.unity3d.com/ScriptReference/Bounds-max.html

1 Answer

1

something like

public float speed;
public Transform[] activeObjects;
public float[] dist;

void Update(){
  for (i int = 0; i < activeObjects.Length; i++){
      dist _= Vector3.Distance(transform.position, activeObject*.position);*_

if(i != 0){
if(dist < dist[i-1]){
transform.position = Vector2.Lerp(transform.position, activeObject_.position, Time.deltaTime * speed);
}else{
transform.position = Vector2.Lerp(transform.position, activeObject[i-1].position, Time.deltaTime * speed);
}
}
}
}
I haven’t tested this, but it should work. Attach it to the object that is going to move toward the closest objects._