# calculating the midpoint of two objects

i am trying to make an object go to the midpoint of two characters in my game and stay there but its not working, here’s my script:

``````var mark : Transform;
var josh : Transform;

function Update () {
transform.position.x = josh.position.x + (mark.position.x - josh.position.x /2);
transform.position.y = josh.position.y + (mark.position.y - josh.position.y /2);
transform.position.z = josh.position.z + (mark.position.z - josh.position.z /2);
}
``````

whenever i start the game the sphere just goes way off screen, does anyone know what im doing wrong?

In programming and math, division is always evaluated before subtraction.

``````(mark.position.x - josh.position.x /2)
``````

is exactly the same as

``````mark.position.x - (josh.position.x /2)
``````

``````transform.position.x = josh.position.x + (mark.position.x - josh.position.x) / 2;
``````

Since this is still the first answer I found on Google in 2021, I decided to add a shorter solution, using Unity’s Vector3.Lerp() to interpolate between two positions.

``````transform.position = Vector3.Lerp(josh.position, mark.position, 0.5f);
``````

This method could also be used for any division other than 1/2.

The midpoint of A and B is (A+B)/2. You have A+B-A/2;

Try:
transform.position = (josh.position + mark.position)/2;

In my current project, my enemies need to judge the distance to 2 different vector position on the players. in order to determine if they are facing them or not. But I want them to “target” and run to a point between those two vectors. Here is how I did that:

``````[Range(0,1)]
public float myFloatVariable;  // can precisely place the spot to "target" in editor.
public Vector3 drawPointOnCurrentTarget;

Vector3 a = new Vector3(GameObjectRepresentingFace.x, GameObjectRepresentingFace.y);
Vector3 b = new Vector3(GameObjectRepresentingBody.x, GameObjectRepresentingBody.y);
drawPointOnCurrentTarget = a + ((b - a).normalized * myFloatVariable);
float distanceToTarget = Vector3.Distance(drawPointOnCurrentTarget, transform.position);
Debug.DrawLine(drawPointOnCurrentTarget, transform.position, Color.red);
``````

Hope this helps someone stumbling onto this question.