Starting to code my own Library

I took the challenge and build on it.

Unity doesn’t have a SqrDistance method so I took this chance to start building my own library for future games: Here’s a little extension for the Transform class that checks if it’s in range of another vector.

    public static bool InRange(this Transform trans, Vector3 target, float range)
    {
        range = Mathf.Pow(range, 2);
        float squareMagnitude = (trans.position - target).sqrMagnitude;
        return squareMagnitude < range;
    }

I’ll be adding more to this library as I progress through the course.

5 Likes

Hey Yee! How are you? Awesome job like always! What have you been up to?

1 Like

Nice work Yee!
Building a library of handy utility functions like this is definitely a great idea and can vastly speed up development of your future projects (it’s only a few lines of code but it’s a few that you never have to write again!)

For a small performance boost, try replacing range = Mathf.Pow(range,2) with range *= range.
Since you’re only squaring a value, you don’t really need the extra overhead and error checking that Math.Pow gives you.

2 Likes

@garypettie Thanks for the tip, I’ll definitely change that!

@Kevin-Brandon I’m “taking a break” from game development, I have like 22 courses I even haven’t started, I want to finish all before moving forward with my projects.

I have dug up some 2D coding solutions for Unity. Here are the links:
Magnitude
Square Magnitude
Distance
(couldn’t find any Square Distance)

1 Like

Privacy & Terms