紧接上part,游戏界面有了,接下来就要构建游戏角色了,先从玩家自身开始吧!!!
我们将用这个作为玩家操控的对象(右键另存为可以下载,记得要拷贝到项目的images文件夹里去):
另外我们需要创建一个基类,让玩家弹板去继承(以后的敌人弹板还有弹球也是继承这个基类)
这个基类名为VisibleGameObject.h,其代码如下:
#pragma once class VisibleGameObject { public: VisibleGameObject(); virtual ~VisibleGameObject(); virtual void Load(std::string filename); virtual void Draw(sf::RenderWindow & window); virtual void SetPosition(float x, float y); private: sf::Sprite _sprite; //存储图片 sf::Texture _image; //读取图片 std::string _filename; //图片路径 bool _isLoaded; //读取是否成功 };
如果不清楚virtual虚函数的用法的话,这里有个简单的例子
struct BaseWithVirtual { virtual void DoSomething() { cout << "Doing something in the base class"; } }; struct DerivedFromVirtual : BaseWithVirtual { void DoSomething() { cout << "Doing something in the derived class"; } }; int main(int argc, char *argv[]) { BaseWithVirtual * bwv = new DerivedFromVirtual(); bwv->DoSomething(); //这里输出的是"Doing something in the derived class" return 0; } struct BaseClass { void DoSomething() { cout << "Doing something in base class"; } }; struct DerivedClass : BaseClass { void DoSomething() { cout << "Doing something in derived class"; } }; int main(int argc, char* argv[]) { BaseClass * bcp = new DerivedClass(); bcp->DoSomething(); //这里输出的是"Doing something in base class" return 0; }
还有VisibleGameObject.cpp
#include "StdAfx.h" #include "VisibleGameObject.h" //函数初始化列表,确保成员变量在构造函数之前就被初始化 VisibleGameObject::VisibleGameObject() : _isLoaded(false) { } VisibleGameObject::~VisibleGameObject() { } void VisibleGameObject::Load(std::string filename) { if(_image.loadFromFile(filename) == false) { _filename = ""; _isLoaded = false; } else { _filename = filename; _sprite.setTexture(_image); _isLoaded = true; } } void VisibleGameObject::Draw(sf::RenderWindow & renderWindow) { if(_isLoaded) { renderWindow.draw(_sprite); } } void VisibleGameObject::SetPosition(float x, float y) { if(_isLoaded) { _sprite.setPosition(x,y); } }
接下来就为玩家弹板创建一个类并继承VisibleGameObject,其名为PlayerPaddle.h,代码如下
#pragma once #include "VisibleGameObject.h" class PlayerPaddle : public VisibleGameObject { public: PlayerPaddle(void); ~PlayerPaddle(void); };
当然还有PlayerPaddle.cpp
#include "StdAfx.h" #include "PlayerPaddle.h" PlayerPaddle::PlayerPaddle(void) { } PlayerPaddle::~PlayerPaddle(void) { }
看起来这个类是什么都没有做。。。。。。。。。。。除了继承之外
最后我们还需要做一些更改以把玩家弹板添加进游戏里面。
在Game.h的private下面添加一句(别忘记include了)
static PlayerPaddle _player1;
在Game.cpp的Start方法中的_gameState = Game::ShowingSplash;之前添加以下代码:
//添加玩家弹板并设置其位置 _player1.Load("images/paddle.png"); _player1.SetPosition((1024/2)-45,700);
GameLoop方法中case Game::Playing:里面的_mainWindow.display();之前把玩家添加到舞台上去
_player1.Draw(_mainWindow);
还要在cpp的最后声明一下,不然编译器会报错的
PlayerPaddle Game::_player1;
如果觉得上面说的有点乱的话,完整的Game类代码在这里可以下载
赶快按F5试试吧~~~~