Convert a “normal” rectangle to a set of GLes vect

2019-07-30 15:54发布

How would I convert a "normal" rectangle into a set of OpenGL ES vertices. I'm not good at geometry so I have no idea how vertices work, and I want to be able to manipulate rectangles without having to work out the values for the vertices by trial and error.

I basically need to convert this structure:

typedef struct __nrect {
    float width;
    float height;
    float depth;

    /* center */
    float x;
    float y;
    float z;
} simple3dRect;

To something like this:

    const GLfloat cubeVertices[6][12] = {
    { 1,-1, 1, -1,-1, 1,  1, 1, 1, -1, 1, 1 },
    { 1, 1, 1,  1,-1, 1,  1, 1,-1,  1,-1,-1 },
    {-1, 1,-1, -1,-1,-1, -1, 1, 1, -1,-1, 1 },
    { 1, 1, 1, -1, 1, 1,  1, 1,-1, -1, 1,-1 },
    { 1,-1,-1, -1,-1,-1,  1, 1,-1, -1, 1,-1 },
    { 1,-1, 1, -1,-1, 1,  1,-1,-1, -1,-1,-1 },
};

Is there an easy way to do this?

1条回答
甜甜的少女心
2楼-- · 2019-07-30 16:45

Assuming that the resulting cube is axis-aligned and that width corresponds to the x-axis, height to the y-axis and depth to the z-axis:

const GLfloat cubeVertices[6][12] = {
    { x + width/2, y - height/2, z + depth/2,  x - width/2, y - height/2, z + depth/2,  x + width/2, y + height/2, z + depth/2,  x - width/2, y + height/2, z + depth/2 },
    { x + width/2, y + height/2, z + depth/2,  x + width/2, y - height/2, z + depth/2,  x + width/2, y + height/2, z - depth/2,  x + width/2, y - height/2, z - depth/2 },
    { x - width/2, y + height/2, z - depth/2,  x + width/2, y - height/2, z - depth/2,  x - width/2, y + height/2, z + depth/2,  x - width/2, y - height/2, z + depth/2 },
    { x + width/2, y + height/2, z + depth/2,  x - width/2, y + height/2, z + depth/2,  x + width/2, y + height/2, z - depth/2,  x - width/2, y + height/2, z - depth/2 },
    { x + width/2, y - height/2, z - depth/2,  x - width/2, y - height/2, z - depth/2,  x + width/2, y + height/2, z - depth/2,  x - width/2, y + height/2, z - depth/2 },
    { x + width/2, y - height/2, z + depth/2,  x - width/2, y - height/2, z + depth/2,  x + width/2, y - height/2, z - depth/2,  x - width/2, y - height/2, z - depth/2 },
};

Clearly, this can be simplified/optimised by pre-computing the width/2, etc. values, longhand included here for clarity.

查看更多
登录 后发表回答