2010-11-30 31 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)坐标三元组)将对诸如着色器优化等事情非常有用。