I'm using a Lua API. I'm trying to transform 3D space coordinates to 2D space coordinates. I've asked google but I can't find anything apart 开发者_如何学Cfrom snippets using OpenGL function. I don't need source code or anything just a simple way on how to do it? I can acquire the Camera's perspective, the original position to be transformed, window size and aspect ratio if that's any help? Thanks in advance for any suggestions :)
If you're talking about transforming world-space (x,y,z) coordinates to screen-space (u,v) coordinates, then the basic approach is:
u = x / z;
v = y / z;
If the camera is not at the origin, transform (x,y,z) by the view matrix before the projection matrix. You may also want to adjust for the camera perspective, aspect ratio etc., in which case I'd refer to this Wikipedia article.
My apologies if you're looking for something specific to the Lua API, which I am not familiar with.
For 3d projection you will need a line of field of view. For example on a 400*400 window ; 200 will be ok. As you can see in the given image. Actually you can increase or decrease this 200 value according to your screen size because using wrong value can stretch your 3d model.
IMAGE
So you can use the given formula to convert your 3d points to 2d points.
Here, x or y means new x or y coordinate after perspective projection and oldx and oldy means old x and y coordinates.
x=(200÷(200+z))*(oldx);
Same formula for y also.
Y=(200÷(200+z))*(oldy);
Here is a java code example for converting 3d coordinates to 2d coordinates with depth of z axis.
// 'double[] a' indicates your 3d coordinates.eg: a=[x,y,z];
// int b indicates whether you wanted to return your 2d x coordinate or y coordinate. 0 will return x and 1 will return y.
// if your image stretches then you can adjust the fovl(field of view line).
public static double PERSPECTIVE_PROJECTION(double[] a,int b){
int fovl=200;
double oldpos=a[b];
double z=a[2];
double newpos=(double)(fovl/(fovl+z))*oldpos;
return newpos;
}
精彩评论