Unity3D/C#–Check If In Distance

Here’s a code snippet for checking if an object is within a certain distance. This will return ‘true’ or ‘false’. Basically it’ll work like this: “If character is within 5 units of another, then he can speak to that character”

public static bool CheckInDist(float dist, GameObject con1, GameObject con2)
    {
        var pos1 = con1.transform.position;
       var pos2 = con2.transform.position;

        var posx = pos1.x – pos2.x;
        var posy = pos1.y – pos2.y;
       var posz = pos1.z – pos2.z;

       if (posx < dist && posx > -dist && posy < dist && posy > -dist && posz < dist && posz > -dist)
        {
            return true;
        }
        else
            return false;
    }

Dist = Distance to check

Con1 = First Game Object to check

Con2 = Second Game Object to check

Advertisements

One comment


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s