Announcement

Collapse
No announcement yet.

How to find the ViewMatrix

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to find the ViewMatrix

    In a 3d game the ViewMatrix is an array of 16 floats that defines your location in the world and your current viewport:


    If you want to convert 3d coordinates into 2d coordinates in order to draw on your screen you have to find the ViewMatrix which can be difficult for beginners. I made a tutorial to show you the basic concept:



    Upon finding the viewmatrix you must "transform" the coordinates by doing some matrix math outlined in this picture:


    A World to Screen transformation function looks like this:
    Code:
    bool WorldToScreen(float * mvpmatrix, Vec3D pos, Vec3D &playerScreenCoords)
    {
    	//Matrix-vector Product, multiplying world(eye) coordinates by projection matrix = clipCoords
    	Vec4D clipCoords;
    	clipCoords.x = pos.x*mvpmatrix[0] + pos.y*mvpmatrix[4] + (pos.z)*mvpmatrix[8] + mvpmatrix[12];
    	clipCoords.y = pos.x*mvpmatrix[1] + pos.y*mvpmatrix[5] + (pos.z)*mvpmatrix[9] + mvpmatrix[13];
    	clipCoords.z = pos.x*mvpmatrix[2] + pos.y*mvpmatrix[6] + (pos.z)*mvpmatrix[10] + mvpmatrix[14];
    	clipCoords.w = pos.x*mvpmatrix[3] + pos.y*mvpmatrix[7] + (pos.z)*mvpmatrix[11] + mvpmatrix[15];
    
    	if (clipCoords.w < 0.1f)
    		return false;
    
    	//perspective division, dividing by clip.W = NDC
    	Vec3D normalizedDeviceCoordinates;
    	normalizedDeviceCoordinates.x = clipCoords.x / clipCoords.w;
    	normalizedDeviceCoordinates.y = clipCoords.y / clipCoords.w;
    	normalizedDeviceCoordinates.z = clipCoords.z / clipCoords.w;
    
    	//viewport tranform to screenCooords
    	playerScreenCoords.x = (windowWidth / 2 * normalizedDeviceCoordinates.x) + (normalizedDeviceCoordinates.x + windowWidth / 2);
    	playerScreenCoords.y = -(windowHeight  / 2 * normalizedDeviceCoordinates.y) + (normalizedDeviceCoordinates.y + windowHeight / 2);
    
    	return true;
    }
    Last edited by [GH]Rake; 04-14-2016, 10:12:19 AM.
Working...
X