2010-11-30 65 views
2

我是新的C++ 3D,所以我可能只是缺少明顯的東西,但我怎麼從3D轉換爲2D和(對於給定的Z位置),從2D到3D?C++圖形編程

+0

你會使用這個呢?爲了利用硬件加速並處理大量支持代碼,您需要學習API。 – tenfour 2010-11-30 10:33:58

+2

這不是一個C++問題。這是一個幾何和矩陣數學問題,或者是關於特定庫或API的問題 - 但C++中沒有標準的3D圖形API。最有可能的是DirectX和OpenGL,儘管你可能正在處理一些更高級的圖層,比如Ogre3D。 – Steve314 2010-11-30 10:34:28

回答

4

您的3D地圖通過projection到2D。通過在矢量的Z元素中插入適當的值,可以將2D映射到3D。

-1

一級跛的解決方案:

^ y 
| 
| 
| /z 
|/
+/--------->x 

角牛和奧茲之間的角度軸(

#include <cmath> 

typedef struct { 
    double x,y,z; 
} Point3D; 

typedef struct { 
    double x,y; 
} Point2D 

const double angle = M_PI/4; //can be changed 

Point2D* projection(Point3D& point) { 
    Point2D* p = new Point2D(); 
    p->x = point.x + point.z * sin(angle); 
    p->y = point.y + point.z * cos(angle); 
    return p; 
} 

但是有很多在網絡上對這個教程的...你用Google搜索呢?

0

這是鑄造從畫面的光線在平行於XY和在需要的位置ž飛機的問題。然後,你需要找出飛機上的光線碰撞。
這裏的一個例子中,考慮到screen_x和screen_y從範圍[0,1],其中0是最左邊的或最頂部座標和1最右邊的最底部,分別或是:

Vector3 point_of_contact(-1.0f, -1.0f, -1.0f); 
Matrix4 view_matrix = camera->getViewMatrix(); 
Matrix4 proj_matrix = camera->getProjectionMatrix(); 
Matrix4 inv_view_proj_matrix = (proj_matrix * view_matrix).inverse(); 
float nx = (2.0f * screen_x) - 1.0f; 
float ny = 1.0f - (2.0f * screen_y); 
Vector3 near_point(nx, ny, -1.0f); 
Vector3 mid_point(nx, ny, 0.0f); 
// Get ray origin and ray target on near plane in world space 
Vector3 ray_origin, ray_target; 
ray_origin = inv_view_proj_matrix * near_point; 
ray_target = inv_view_proj_matrix * mid_point; 

Vector3 ray_direction = ray_target - ray_origin; 
ray_direction.normalise(); 

// Check for collision with the plane 
Vector3 plane_normal(0.0f, 0.0f, 1.0f); 
float denominator = plane_normal.dotProduct(ray_direction); 
if (fabs(denom) >= std::numeric_limits<float>::epsilon()) 
{ 
    float num = plane_normal.dotProduct(ray.getOrigin()) + Vector3(0, 0, z_pos); 
    float distance = -(num/denom); 
    if (distance > 0) 
    { 
     point_of_contact = ray_origin + (ray_direction * distance); 
    } 
} 
return point_of_contact 

免責聲明:該解決方案取自Ogre3D圖形庫的零碎部分。

0

最簡單的方法是用Z做除法。因此...

screenX = projectionX/projectionZ; 
screenY = projectionY/projectionZ; 

這是基於距離的透視投影。事情是它往往是更好地使用homgeneous coordinates因爲這樣簡化矩陣變換(一切都變得乘法)。同樣,這也是D3D和OpenGL使用的。理解如何使用非齊次座標(即(x,y,z)座標三元組)將對諸如着色器優化等事情非常有用。