Distance Between 2 Objects Without Y

I'll try to explain this as best I can. I have an enemy which will start running towards the Player if he's a certain distance away from it. This works fine, but the problem is that when the Player jumps, the Enemy thinks that the Player is far away because the Distance goes up because transform.position factors in the Y value. I basically need the enemy to calculate the distance between it and the Player without factoring in the Player's Y value in order to keep the enemy grounded. The way it works now, the enemy stops at the stop range, but if the player jumps he starts running underneath the player and into the sky.

Here's the distance calculation script:

var distanceToTarget = Vector3.Distance(transform.position, GameObject.FindWithTag("Player").transform.position);

Here's the following script:

function Patrol(){
        if( AttackRangeCheck() ){ // target object is within range
            if( !StopRangeCheck()){
                var newPos = Vector3(GameObject.FindWithTag("Player").transform.position.x, 0, GameObject.FindWithTag("Player").transform.position.z);
                isRunning = true;

Vector3.Distance just subtracts position two from position one and returns the vector length (magnitude).

var dist = Vector3.Distance(P1,P2);

would be the same as

var dist = (P2-P1).magnitude;

So you can calculate the vector yourself and before you get the magnitude just set y to 0:

var vectorToTarget = GameObject.FindWithTag("Player").transform.position - transform.position;
vectorToTarget.y = 0;
var distanceToTarget = vectorToTarget.magnitude;

ps. It doesn't matter whether you subtract P1 from P2 or P2 from P1, the resulting vector would just point in the opposite direction but the length (magnitude) will be the same.

It would probably be easy to just nullify the data on the y-axis and then do a distance test, like so:

Vector3 my2dPos = transform.position;
my2dPos.y = 0;
Vector3 target2dPos = GameObject.FindWithTag("Player").transform.position;
target2dPos.y = 0;
var distanceToTarget = Vector3.Distance(my2dPos, target2dPos);

You could also use Vector2, but you'd have to be careful because that would get rid of the z-value as opposed to the y-value.

Then the only concern is when you have a situation where the two are very close to each other on the x-z plane, but are separated by a large height, like on the edge of a cliff. You'd probably want to have some y distance at which you no longer allow the enemy to follow the player, like a little less than the distance it would take to kill the enemy.

I’ll keep it simple.

	public static float FlatDistance(Vector3 pos1, Vector3 pos2)
		pos1.y = pos1.z;
		pos2.y = pos2.z;
		return Vector2.Distance(pos1, pos2);