diff options
| author | Ray <raysan5@gmail.com> | 2016-01-11 19:47:17 +0100 |
|---|---|---|
| committer | Ray <raysan5@gmail.com> | 2016-01-11 19:47:17 +0100 |
| commit | bb49102a4b5ae7bf6a34b437b133e8c5e3557f8d (patch) | |
| tree | dad410c2320a3a2b021c724d3b512a17d83cdf5d /src/core.c | |
| parent | 5e7686695fcfe32bbf956990ced0a02b7c881af1 (diff) | |
| parent | 4cc394c376c83926da67afe14855d2a3e2b06cfd (diff) | |
| download | raylib-bb49102a4b5ae7bf6a34b437b133e8c5e3557f8d.tar.gz raylib-bb49102a4b5ae7bf6a34b437b133e8c5e3557f8d.zip | |
Merge pull request #73 from victorfisac/develop
World to screen conversion and little review
Diffstat (limited to 'src/core.c')
| -rw-r--r-- | src/core.c | 30 |
1 files changed, 29 insertions, 1 deletions
@@ -791,7 +791,7 @@ int StorageLoadValue(int position) return value; } -// Gives the ray trace from mouse position +// Returns a ray trace from mouse position //http://www.songho.ca/opengl/gl_transform.html //http://www.songho.ca/opengl/gl_matrix.html //http://www.sjbaker.org/steve/omniv/matrices_can_be_your_friends.html @@ -857,6 +857,34 @@ Ray GetMouseRay(Vector2 mousePosition, Camera camera) return ray; } +// Returns the screen space position from a 3d world space position +Vector2 WorldToScreen(Vector3 position, Camera camera) +{ + // Calculate projection matrix (from perspective instead of frustum + Matrix matProj = MatrixPerspective(45.0f, (float)((float)GetScreenWidth() / (float)GetScreenHeight()), 0.01f, 1000.0f); + + // Calculate view matrix from camera look at (and transpose it) + Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); + MatrixTranspose(&matView); + + // Convert world position vector to quaternion + Quaternion worldPos = { position.x, position.y, position.z, 1.0f }; + + // Transform world position to view + QuaternionTransform(&worldPos, matView); + + // Transform result to projection (clip space position) + QuaternionTransform(&worldPos, matProj); + + // Calculate normalized device coordinates (inverted y) + Vector3 ndcPos = { worldPos.x / worldPos.w, -worldPos.y / worldPos.w, worldPos.z / worldPos.z }; + + // Calculate 2d screen position vector + Vector2 screenPosition = { (ndcPos.x + 1.0f) / 2.0f * GetScreenWidth(), (ndcPos.y + 1.0f) / 2.0f * GetScreenHeight() }; + + return screenPosition; +} + //---------------------------------------------------------------------------------- // Module Functions Definition - Input (Keyboard, Mouse, Gamepad) Functions //---------------------------------------------------------------------------------- |
