美文网首页
三、OpenGL绘制正方形并移动

三、OpenGL绘制正方形并移动

作者: fred风飘 | 来源:发表于2020-07-06 00:35 被阅读0次

    一、绘制流程

    image.png

    二、定义正方形顶点数据

    blockSize为变长的一半

    //blockSize 边长
    GLfloat blockSize = 0.1f;
    
    //正方形的4个点坐标
    GLfloat vVerts[] = {
            -blockSize,-blockSize,0.0f,
            blockSize,-blockSize,0.0f,
            blockSize,blockSize,0.0f,
            -blockSize,blockSize,0.0f
    };
    
    image.png

    三、键位控制
    当正方形上下左右移动的时候,需要更新正方形的位置

    实现方式有两种:
    1、坐标更新,手动计算每个顶点的位置

        GLfloat stepSize = 0.025f;
        
        GLfloat blockX = vVerts[0];
        GLfloat blockY = vVerts[10];
        
        printf("v[0] = %f\n",blockX);
        printf("v[10] = %f\n",blockY);
        
        
        if (key == GLUT_KEY_UP) {
            
            blockY += stepSize;
        }
        
        if (key == GLUT_KEY_DOWN) {
            
            blockY -= stepSize;
        }
        
        if (key == GLUT_KEY_LEFT) {
            blockX -= stepSize;
        }
        
        if (key == GLUT_KEY_RIGHT) {
            blockX += stepSize;
        }
    
        //触碰到边界(4个边界)的处理
        
        //当正方形移动超过最左边的时候
        if (blockX < -1.0f) {
            blockX = -1.0f;
        }
        
        //当正方形移动到最右边时
        //1.0 - blockSize * 2 = 总边长 - 正方形的边长 = 最左边点的位置
        if (blockX > (1.0 - blockSize * 2)) {
            blockX = 1.0f - blockSize * 2;
        }
        
        //当正方形移动到最下面时
        //-1.0 - blockSize * 2 = Y(负轴边界) - 正方形边长 = 最下面点的位置
        if (blockY < -1.0f + blockSize * 2 ) {
            
            blockY = -1.0f + blockSize * 2;
        }
        
        //当正方形移动到最上面时
        if (blockY > 1.0f) {
            
            blockY = 1.0f;
            
        }
    
        printf("blockX = %f\n",blockX);
        printf("blockY = %f\n",blockY);
        
        // Recalculate vertex positions
        vVerts[0] = blockX;
        vVerts[1] = blockY - blockSize*2;
        printf("(%f,%f)\n",vVerts[0],vVerts[1]);
        
        vVerts[3] = blockX + blockSize*2;
        vVerts[4] = blockY - blockSize*2;
        printf("(%f,%f)\n",vVerts[3],vVerts[4]);
        
        vVerts[6] = blockX + blockSize*2;
        vVerts[7] = blockY;
        printf("(%f,%f)\n",vVerts[6],vVerts[7]);
        
        vVerts[9] = blockX;
        vVerts[10] = blockY;
        printf("(%f,%f)\n",vVerts[9],vVerts[10]);
    

    2、矩阵计算,提供一个顶点x、y轴位置,通过矩阵批量计算,适用于多顶点的图形


    image.png

    三、代码实现
    链接: https://pan.baidu.com/s/1sqglgDskdgWa4tVQbF232g 提取码: 7dfy

    相关文章

      网友评论

          本文标题:三、OpenGL绘制正方形并移动

          本文链接:https://www.haomeiwen.com/subject/zhtvqktx.html