Originally Posted by
newbiehacker
Hello,
I am trying to convert 3D World Coordinates to 2D Screen Coordiantes. Basically I am trying to draw boxes around ennemy players...
So far I have achieved to get the following data: FOV, My ViewAngle, My Position in 3D, Ennemy Position in 3D
How can I calculate where to draw the box on the Screen now so it is drawn on the ennemy player?
You will need camera position, camera look at vector, fov, aspect ratio, nearclip and farclip.
With this data build a right handed look at and perspective matrix:
look at rh
Code:
zaxis = normal(Eye - At)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)
xaxis.x yaxis.x zaxis.x 0
xaxis.y yaxis.y zaxis.y 0
xaxis.z yaxis.z zaxis.z 0
dot(xaxis, eye) dot(yaxis, eye) dot(zaxis, eye) 1
perspective rh
Code:
xScale 0 0 0
0 yScale 0 0
0 0 zf/(zn-zf) -1
0 0 zn*zf/(zn-zf) 0
where:
yScale = cot(fovY/2)
xScale = yScale / aspect ratio
Then calculate the current transformation matrix with Identity (World) * View * Projection.
Code:
Utils::Matrix44 mTransform = mWorld * mView * mProjection;
Utils::Vector3 vScreen = mTransform * vPosition;
The screen vector will contain normalized positions between -1 (most left point on screen) to +1 (most right point on screen) so you need to scale that with your viewport and you're good.
EDIT:
For screen to world just do it the other way round. Take your screen position vectors and bring it to a -1 / +1 format then multiply it by the inverse projection:
Code:
Utils::Matrix44 mInverse = mWorld.inverse() * mView.inverse() * mProjection.inverse();
Utils::Vector3 vPosition = mInverse * vScreen;