Need someone to verify that my math is correct
I've been sitting with a pencil for the better part of the evening trying to recall how to implement a scalable viewport that can navigate a 2D area. It's been a while since I've first heard of it, but I think I've figured it out, I just need to verify.
We have a 2D world with a "classic" cartesian coordinate system, x-axis points to the right, y-axis points to the top.
In the world area we have a rectangular viewport defined by 2 points Pmin and Pmax, where : Pmin(xmin, ymin), Pmax(xmax, ymax). Those points define viewport's size, location and scale
In the world area we have a point P, where Pmin < P(x, y) < Pmax. (P is in the viewport rect)
To display the whole damn thing, we've got a canvas (for example) that has an "altered" coordinate system, x-axis points right, y-axis points down. The canvas's size is MaxX and MaxY. The canvas's size is fixed.
Now, in order to display point P'(x', y') in the canvas I need to calculate it's position like this :
x' = (x - xmin) * Sx
, where Sx = MaxX / (xmax - xmin)
y' = MaxY - (y - ymin) * Sy
, where Sy = MaxY / (ymax - ymin)
*please note that y' coord is inverted due to canvas's coordinate system
In other words : the above math should take care of displaying a point while taking scale and 开发者_Python百科vieport's position into account. Am I correct ? If not, please prove me wrong.
Yes, that is correct. All points in the viewport will appear on the canvas -- and only those points -- and everything will appear right-side-up with distances preserved.
You may find it useful to create a class for the viewport which manages the scale and ranges. It can have methods such as
Point2 vp = viewport.transformFromWorld(Point2 pw);
and the inverse:
Point2 pw = viewport.transformToWorld(Point2 vp);
This is useful if you pick a point in the viewpoint with viewport coordinates and wish to transform to world.
精彩评论