系列三:OPENGL我来了
Posted unicornsir
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了系列三:OPENGL我来了相关的知识,希望对你有一定的参考价值。
完成系列二后,心里相当激动,如果能看到精美的游戏动画多好......
这不是做梦,有梦想就能实现,但是我们还是一步一步来,先来看一下显示普通的图形
注:在此版本里,用了最容易的老式OPENGL,后面接下来用的是新式的moden opengl
MainGame.h
1 #pragma once 2 #include <SDL/SDL.h> 3 #include <GL/glew.h> 4 5 enum class GameState{PLAY, EXIT}; 6 7 class MainGame 8 { 9 public: 10 MainGame(); 11 ~MainGame(); 12 13 void run(); 14 15 16 private: 17 void initSystems(); 18 void gameLoop(); 19 void processInput(); 20 void drawGame(); 21 22 SDL_Window* m_pWindow; 23 int m_nScreenWidth; 24 int m_nScreenHeight; 25 GameState m_gameState; 26 };
MainGame.cpp
1 #include "MainGame.h" 2 #include <iostream> 3 #include <string> 4 void faterError(const std::string& errorString) 5 { 6 std::cout << errorString << std::endl; 7 std::cout << "Enter any key to quit..."; 8 std::cin.get(); 9 SDL_Quit(); 10 } 11 12 MainGame::MainGame() :m_pWindow(nullptr), m_nScreenWidth(1024), m_nScreenHeight(768), m_gameState(GameState::PLAY) 13 { 14 15 } 16 17 18 MainGame::~MainGame() 19 { 20 } 21 22 void MainGame::run() 23 { 24 initSystems(); 25 26 gameLoop(); 27 } 28 29 void MainGame::initSystems() 30 { 31 //Initialize SDL 32 SDL_Init(SDL_INIT_EVERYTHING); 33 m_pWindow = SDL_CreateWindow("GraphicToturial", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, m_nScreenWidth, m_nScreenHeight, SDL_WINDOW_OPENGL); 34 if (nullptr == m_pWindow) 35 { 36 faterError("SDL Window could not be created!"); 37 } 38 39 SDL_GLContext glContext = SDL_GL_CreateContext(m_pWindow); 40 if (nullptr == glContext) 41 { 42 faterError("SDL_GL context could not be created!"); 43 } 44 45 GLenum result = glewInit(); 46 if (GLEW_OK != result) 47 { 48 faterError("Could not initialize glew!"); 49 } 50 51 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 52 53 glClearColor(0, 0, 1, 1); 54 } 55 56 void MainGame::gameLoop() 57 { 58 while (m_gameState != GameState::EXIT) 59 { 60 processInput(); 61 drawGame(); 62 } 63 } 64 65 void MainGame::processInput() 66 { 67 SDL_Event evnt; 68 while (SDL_PollEvent(&evnt)) 69 { 70 switch (evnt.type) 71 { 72 case SDL_QUIT: 73 m_gameState = GameState::EXIT; 74 break; 75 case SDL_MOUSEMOTION: 76 std::cout << evnt.motion.x << " " << evnt.motion.y << std::endl; 77 break; 78 } 79 } 80 } 81 82 void MainGame::drawGame() 83 { 84 glClearDepth(1.0); 85 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 86 87 glEnableClientState(GL_COLOR_ARRAY); 88 glColor3f(1.0f, 0.0f, 0.0f); 89 glBegin(GL_TRIANGLES); 90 glVertex2f(0.0f, 0.0f); 91 glVertex2f(0.0f, 500.0f); 92 glVertex2f(500.f, 500.0f); 93 glEnd(); 94 95 SDL_GL_SwapWindow(m_pWindow); 96 }
以上是关于系列三:OPENGL我来了的主要内容,如果未能解决你的问题,请参考以下文章
百万粉女极客突袭深圳手机公司:你们说想要源码就来自取?我来了
百万粉女极客突袭深圳手机公司:你们说想要源码就来自取?我来了