Anixias
Member
Hello. I found online that in order to convert a 3D point to a 2D vector representing a point on your screen, you must:
It works perfectly if the 3D point is the lookat point of the View Matrix, but if it isn't, it will be slightly off, and the error is amplified the more zoomed in the camera is to the 3D point.
Now, I decided to temporarily ignore this issue and try 2D screen coordinate to 3D vector conversion. The result is just... odd? Here is that script:
The X-Coordinate was negative even when pointing my mouse towards the lookat-vector (which is the reason for the next-to-last line). The vector itself, in relation to the camera, is facing the opposite way. I simply subtract the vector returned by this script by the camera position vector, normalize it, and then multiply it by 10 so that it is visible. The Y-Coordinate, in relation to the camera, is flipped, so that moving my mouse down on the screen actually moves the 3D point up, rather than down.
What's wrong with my scripts? What are working alternatives, if you have any? Note: I'm using perspective projections, and +Z is up.
- Transform the vec3 (3d point) by the camera's View Matrix
- Transform the vec3 produced by step 1 by the camera's Projection Matrix
- Divide the vec3's x and y values by the z value.
- Convert the x and y value from a range of (-1,1) to a range of (0,screen width/height)
Code:
/// @param x
/// @param y
/// @param z
/// @param viewmat
/// @param projmat
/// @param screenwidth
/// @param screenheight
//Returns a vec2 containing screen coordinates
var vec3;
var xx = argument[0], yy = argument[1], zz = argument[2];
var viewmat = argument[3], projmat = argument[4];
var w = argument[5], h = argument[6];
vec3 = matrix_transform_vertex(viewmat,xx,yy,zz);
vec3 = matrix_transform_vertex(projmat,vec3[0],vec3[1],vec3[2]);
vec3[0] /= vec3[2];
vec3[1] /= vec3[2];
var a;
a[0] = w*(vec3[0]+1)/2;
a[1] = h*(vec3[1]+1)/2;
return a;
Now, I decided to temporarily ignore this issue and try 2D screen coordinate to 3D vector conversion. The result is just... odd? Here is that script:
Code:
/// @param x
/// @param y
/// @param viewmat
/// @param projmat
/// @param screenwidth
/// @param screenheight
//Returns a vec3 containing world coordinates
var vec3;
var xx = argument[0], yy = argument[1];
var viewmat = argument[2], projmat = argument[3];
var w = argument[4], h = argument[5];
var a;
a[0] = 2*(xx/w)-1;
a[1] = 2*(yy/h)-1;
vec3 = matrix_transform_vertex(projmat,a[0],a[1],0);
vec3 = matrix_transform_vertex(viewmat,vec3[0],vec3[1],vec3[2]);
vec3[0] *= -1;
return vec3;
What's wrong with my scripts? What are working alternatives, if you have any? Note: I'm using perspective projections, and +Z is up.
Last edited: