Math Help: Are These Two Functions Inverses?

50 views Asked by At

I'm trying to create two functions to translate from "Zoomed in map space" to "Screen space" for a game. However, I suspect that these two are not exact inverses, because while translating to screen space things work fine, but translating back from screen space doesn't quite work.

So, are these two inverses? If not, what needs to change?

        public Point ShrinkPos(int scale, Point pos)
    {

        Point newPos = pos + Globals.currentCampLocation + new Point(10, 10);
        pos.X = (newPos.X / scale) + ((tileSize.X / scale) * 2);
        pos.Y = (newPos.Y / scale) + (tileSize.Y / scale);
        pos.X -= (offset.X / scale) * 2;
        pos.Y -= offset.Y / scale;
        return pos;
    }


    public Point ExpandPos(int scale, Point pos)
    {
        Point newPos = pos - Globals.currentCampLocation - new Point(10, 10);
        pos.X = (newPos.X * scale) - ((tileSize.X * scale) / 2);
        pos.Y = (newPos.Y * scale) - (tileSize.Y * scale);
        pos.X += (offset.X * scale) / 2;
        pos.Y += (offset.Y * scale);
        return pos;
    }
1

There are 1 answers

1
Yakk - Adam Nevraumont On

Generally you want to invert operations in the opposite order.

Ie, if you did

x = x+2
x = x*2

the inverse operation is

x = x/2
x = x-2

however, your logic fails to reverse the order.

There may be other glitches, but that will result in errors.

...

Most coordinate transformations you need for this kind of thing can be expressed as a matrix, sometimes in projective space to get translations working.

Then matrix inverse mechanical operations can make inversion reliable.