6. GameObject

为什么需要

一个游戏包含很多对象, 如NPC(non-player character), 怪物, 子弹, 门等. 如果包含这么多对象, 如果管理就成了问题, 这里就用到C++中OOP(Object-Oriented Programming).

上代码

OO的一个难点是如何开始. 我们可以简单分析一下. 游戏中所有对象的共性是什么, 将这些抽出来就能简单的形成一个基类, 然后进行细化调整. 首先看一下共性:

  1. 都要有自己的绘制方法
  2. 都有位置和大小信息
  3. 都需要更新自己的状态信息
  4. 游戏结束, 释放自己的资源

我们根据上面的几条, 抽成如下代码:

// GameObject.h
#ifndef GAMEOBJECT_H_INCLUDED
#define GAMEOBJECT_H_INCLUDED

#include "SDL.h"
#include <string>

class GameObject
{
public:
    void load(int x, int y, int width, int height, std::string textureID);
    void draw(SDL_Renderer* pRenderer);
    void update();
    void clean();

protected:
    std::string m_textureID;

    int m_currentFrame;
    int m_currentRow;

    int m_x;
    int m_y;

    int m_width;
    int m_height;
};

#endif // GAMEOBJECT_H_INCLUDED
// GameObject.cpp
#include "GameObject.h"
#include "TextureManager.h"

void GameObject::load(int x, int y, int width, int height, std::string textureID)
{
    m_x = x;
    m_y = y;

    m_width = width;
    m_height = height;

    m_textureID = textureID;

    m_currentRow = 1;
    m_currentFrame = 1;
}


void GameObject::draw(SDL_Renderer* pRenderer)
{
    TextureManager::Instance()->drawFrame(m_textureID, m_x, m_y, m_width, m_height,
                                          m_currentRow, m_currentFrame, pRenderer);
}

void GameObject::update()
{
    m_x += 1;
    m_currentFrame = (SDL_GetTicks()/50) % 6;
}

然后对Game.h和Game.cpp做对应的修改调整, 编译运行. 能看到一只动物向前奔跑.

后续

有了这样一个基类后, 我们就能利用继承在此基础上新建其他对象. 但是如果仅此而已的话, 我们一个游戏类里会有大量的对象需要去处理. 因此就需要用到多态的特性, 这样我们就只要一个循环来对所有对象进行处理.

猜你喜欢

转载自blog.csdn.net/creambean/article/details/88659289