Using Vector3.distance without the y axis

So I’m using Vector3.distance to work out whenever the player is within a certain range of the enemy so the enemy can start chasing them and it works the way i want it. But the problem is I have some enemy’s on high platforms that the player has to jump onto and once the player is on the same platform, I then want the enemy to start chasing the player.
The problem i have currently is if the player is in range no matter if the enemy is higher then the player or lower, the enemy will start to chase the player which again… is not what i want

So i was wondering if there is a way using Vector3.distance to make it so it doesn’t use the y axis. Or if there is another way i have to do it?

Apart from anything else, you’ll surely want the “FLAT” distance …

this is common, you have such an extension in every project…

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class Extns
	{
	public static Vector2 xz(this Vector3 vv)
		{
		return new Vector2(vv.x, vv.z);
		}
	
	public static float FlatDistanceTo(this Vector3 from, Vector3 unto)
		{
		Vector2 a = from.xz();
		Vector2 b = unto.xz();
		return Vector2.Distance( a, b );
		}
	}

use like this …

float howFar = a.FlatDistanceTo( b );

or perhaps

d = transform.position.FlatDistanceTo( enemyPosition );

It may help.

Something like:

If (Vector3.Distance(enemy.transform.position, player.transform.position) < chaseDistance)
{
    if (Mathf.Abs(player.transform.position.y - enemy.transform.position.y) < heightThreshold)
    {
        //Chase the player
    }
}

Don’t use Vector3.Distance, just subtract x of one from x from the other…

I’ll keep it simple.

public static float DistanceXZ ( Vector3 lhs , Vector3 rhs )
    => Vector2.Distance( new Vector2{x=lhs.x,y=lhs.z} , new Vector2{x=rhs.x,y=rhs.z} );

Edit: fixed

Well the best way to do this use CirlcecastAll for 2D and SphereCastAll for 3D
Using them is the easiest & best Option for you Question
Hope you got this :slight_smile:

//If you want to do same with more than one enemy you need to use CirclecastAll

public float range ; // basically this is the radius 
public LayerMask enemyMask ;  // Set a layer to your enemys and then set the same layer to the enemyMask 

//Other modifications as per ur need
public Vector2 Direction ;
public float distance ;
private Raycast2D _raycast ;

void Range()
{
    //This will cast a circle around Player and detects if the enemy is within range(radius of circlecast)
     _raycast = Physics2D.Circlecast(transform.position , range ,Direction ,distance ,enemyMask );

    //Now you can just apply any thing to your enemy if it comes within range
    if(_raycast) 
    {
        //   TriggerTheEnemyToAttackPlayer
    }
    
}

Read This for understand Concepts(They are quiet best option )

CircleCast - Unity - Scripting API: Physics2D.CircleCastAll
SphereCast - Unity - Scripting API: Physics.SphereCastAll

@Codelyoko363