SDL2 游戏开发日记(八) 按钮、对话框的绘制
在游戏中,会弹出各种各样的对话框,用来显示游戏中的一些信息,或者要求玩家进行相应的输入。
对话框的基类
创建一个纹理,把对话框的背景,按钮都绘制在这个纹理上。如果按钮状态没有发生改变,直接在主循环里绘制这个纹理。如果按钮状态改变,重新绘制纹理后再绘制到主循环里。
#pragma once
#include "Renderable.h"
#include "Button.h"
#include "Common.h"
#include "MessageListener.h"
#include <vector>
using namespace std;
class Dialog : public Renderable{
protected:
//对话框背景
Renderable *mBackground;
//按钮列表
vector<Button *>mButtonList;
//是否需要重绘Texture;
bool mIsChange;
public:
Dialog(){
mBackground = NULL;
}
//创建Texture;
void CreateRenderTexture(int x, int y, int width, int height);
virtual ~Dialog(){
SAFE_DELETE(mBackground);
SDL_DestroyTexture(mTexture);
}
//设置背景
void SetBackground(Renderable*background){
SAFE_DELETE(mBackground);
mBackground = background;
}
//绘图
virtual void Render();
//加载按钮
virtual void LoadButtons(){}
//处理消息
virtual void HandleEvent(SDL_Event &ev);
//处理鼠标消息
void HandleMouseEvent(int eventType, int x, int y);
添加按钮
void AddButton(Button *button){
mButtonList.push_back(button);
}
void Refresh(){
mIsChange = true;
}
};
//Dialog.cpp
#include "stdafx.h"
#include "Dialog.h"
#include "SDLGame.h"
void Dialog::CreateRenderTexture(int x, int y, int width, int height){
mTexture = SDL_CreateTexture(theGame.getRenderer(),
SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
if (mRenderRect == NULL)
mRenderRect = new SDL_Rect();
mTextureWidth = width;
mTextureHeight = height;
mRenderRect->w = width;
mRenderRect->h = height;
SetPos(x, y);
mIsChange = true;
SetLayer(10);
}
void Dialog::HandleEvent(SDL_Event &ev){
if (ev.type == SDL_MOUSEMOTION){
HandleMouseEvent(ev.type,ev.motion.x, ev.motion.y);
}
else if (ev.type == SDL_MOUSEBUTTONDOWN && ev.button.button == SDL_BUTTON_LEFT){
HandleMouseEvent(ev.type,ev.button.x, ev.button.y);
}
else if (ev.type == SDL_MOUSEBUTTONUP && ev.button.button == SDL_BUTTON_LEFT){
Han