Using Mathf.Floor() to ensure equal Y axis

I noticed several people having trouble getting their spawner and defender to line up on the same y axis. I had this problem because one of my defenders needed to be moved up a little and thus they were sitting at ~+0.2 more than the spawner. An easy way to fix this is to use Mathf.Floor(). Essentially it removes the floating point value. Thus 3.2 becomes 3 and -3.2 becomes -4. You can also use Mathf. Ceiling() which has the opposite effect.

I also chose to use Mathf.Approximately() instead of <= Mathf.Epsilon. It’s a bit easier to read and does the same thing. You can also use Math.Round() if some sit a little above and below the center point.

private void SetLaneSpawner()
    {
        // Get all of the spawners
        EnemySpawner[] spawners = FindObjectsOfType<EnemySpawner>();

        foreach(EnemySpawner spawner in spawners) {

            print("Enemey position y Floor " + Mathf.Floor(transform.position.y));
            bool IsInLane = (Mathf.Approximately(spawner.transform.position.y, Mathf.Floor(transform.position.y)));

            if (IsInLane) {
                laneSpawner = spawner;
            }

        }
    }

You can see from my image that the enemy’s y axis is 3.2 but still sees the attacker.

4 Likes

Thanks. I also had to floor spawner.transform.position.y to get it to work because even the spawned attackers were off by 0.4.

Thank you! I know this is an old thread, but this was driving me crazy!

Privacy & Terms