- Home /
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.
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.$$anonymous$$ and Bounds.max).
Answer by Tekksin · Oct 14, 2018 at 05:48 AM
something like
public float speed;
public Transform[] activeObjects;
public float[] dist;
void Update(){
for (i int = 0; i < activeObjects.Length; i++){
dist[i] = Vector3.Distance(transform.position, activeObject[i].position);
if(i != 0){
if(dist[i] < dist[i-1]){
transform.position = Vector2.Lerp(transform.position, activeObject[i].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.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
How do I add forward velocity to a Rigidbody2D? 2 Answers
Controlling the update position of a cloned Gameobject C# 1 Answer
how to make my game object to be at mouse position and then to fall at that position? 1 Answer
Put an offset distance to gameobject that follows player 2 Answers