qiangbizhi 2020-04-16
完成系列二后,心里相当激动,如果能看到精美的游戏动画多好......
这不是做梦,有梦想就能实现,但是我们还是一步一步来,先来看一下显示普通的图形
注:在此版本里,用了最容易的老式OPENGL,后面接下来用的是新式的moden opengl
MainGame.h
#pragma once
#include <SDL/SDL.h>
#include <GL/glew.h>
enum class GameState{PLAY, EXIT};
class MainGame
{
public:
MainGame();
~MainGame();
void run();
private:
void initSystems();
void gameLoop();
void processInput();
void drawGame();
SDL_Window* m_pWindow;
int m_nScreenWidth;
int m_nScreenHeight;
GameState m_gameState;
};MainGame.cpp
#include "MainGame.h"
#include <iostream>
#include <string>
void faterError(const std::string& errorString)
{
std::cout << errorString << std::endl;
std::cout << "Enter any key to quit...";
std::cin.get();
SDL_Quit();
}
MainGame::MainGame() :m_pWindow(nullptr), m_nScreenWidth(1024), m_nScreenHeight(768), m_gameState(GameState::PLAY)
{
}
MainGame::~MainGame()
{
}
void MainGame::run()
{
initSystems();
gameLoop();
}
void MainGame::initSystems()
{
//Initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
m_pWindow = SDL_CreateWindow("GraphicToturial", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, m_nScreenWidth, m_nScreenHeight, SDL_WINDOW_OPENGL);
if (nullptr == m_pWindow)
{
faterError("SDL Window could not be created!");
}
SDL_GLContext glContext = SDL_GL_CreateContext(m_pWindow);
if (nullptr == glContext)
{
faterError("SDL_GL context could not be created!");
}
GLenum result = glewInit();
if (GLEW_OK != result)
{
faterError("Could not initialize glew!");
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
glClearColor(0, 0, 1, 1);
}
void MainGame::gameLoop()
{
while (m_gameState != GameState::EXIT)
{
processInput();
drawGame();
}
}
void MainGame::processInput()
{
SDL_Event evnt;
while (SDL_PollEvent(&evnt))
{
switch (evnt.type)
{
case SDL_QUIT:
m_gameState = GameState::EXIT;
break;
case SDL_MOUSEMOTION:
std::cout << evnt.motion.x << " " << evnt.motion.y << std::endl;
break;
}
}
}
void MainGame::drawGame()
{
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnableClientState(GL_COLOR_ARRAY);
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_TRIANGLES);
glVertex2f(0.0f, 0.0f);
glVertex2f(0.0f, 500.0f);
glVertex2f(500.f, 500.0f);
glEnd();
SDL_GL_SwapWindow(m_pWindow);
}