3D战斗游戏之数据库篇2

2015年03月17日 10:37 0 点赞 0 评论 更新于 2025-11-21 17:15

参考:3D战斗游戏之数据库篇1

在上一个教程中,我们完成了数据库结构设计。在本教程里,将详细阐述如何在游戏中借助数据库调用生成一个场景。

实现这一功能其实并不复杂,只需添加一个 LoadScene() 函数。当在 Cocos 中载入一个 Scene 时,调用 LoadScene() 函数来加载场景所需的全部内容。以下是 LoadScene() 函数的具体实现代码:

void GhostBox::LoadScene()
{
// 根据 scene_id 查询场景数据,并初始化场景
std::map<std::string, std::string> m;
std::vector<std::map<std::string, std::string>> vect = DBHelper::GetTable("select * from scene where scene_id=1");
// log("sqlite-->GetTable returns %d row", vect.size());
m = vect[0];

// 设定场景模型
if (m["scene_3dm"] != "" && m["scene_3dt"] != "" && m["scene_3ds"] != "")
{
std::string fileName = m["scene_3dm"].c_str();
auto sprite = Sprite3D::create(fileName);
sprite->setTexture(m["scene_3dt"].c_str());
sprite->setScale(std::atof(m["scene_3ds"].c_str()));
_layer3D->addChild(sprite);
}

// 设定场景光照
if (m["lighta_r"] != "" && m["lighta_g"] != "" && m["lighta_b"] != "")
{
// 散射光,颜色
_ambientLight = AmbientLight::create(cocos2d::Color3B(std::atoi(m["lighta_r"].c_str()), std::atoi(m["lighta_g"].c_str()), std::atoi(m["lighta_b"].c_str())));
_ambientLight->retain();
_ambientLight->setEnabled(true);
addChild(_ambientLight);
_ambientLight->setCameraMask(2);
}

if (m["lightd_r"] != "" && m["lightd_g"] != "" && m["lightd_b"] != "")
{
// 方向光源,方向/颜色
_directionalLight = DirectionLight::create(cocos2d::Vec3(0.0f, 0.0f, -1.0f), cocos2d::Color3B(std::atoi(m["lightd_r"].c_str()), std::atoi(m["lightd_g"].c_str()), std::atoi(m["lightd_b"].c_str())));
_directionalLight->retain();
_directionalLight->setEnabled(true);
addChild(_directionalLight);
_directionalLight->setCameraMask(2);
}

// 背景音乐
if (m["scene_bgm"] != "")
{
// preload background music and effect
// SimpleAudioEngine::getInstance()->preloadBackgroundMusic(m["scene_bgm"].c_str());
// SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.1);
// SimpleAudioEngine::getInstance()->playBackgroundMusic(m["scene_bgm"].c_str(), true);
}
}

在上述代码中,使用的数据库为 Sqlite,数据库查询借助了网上常见的 DBHelper 类,你可以自行下载使用。

接下来,为了让大家更清晰地了解,这里给出 scene 数据库的相关数据(此处应补充实际数据,如果有)。

除了 LoadScene() 函数,还需要实现 LoadBBLoadBoss 等函数来加载该场景所需的其他元素。掌握了基本方法后,实现这些功能并不困难,只需从数据库中查询数据,然后在程序中进行绘制即可。

当依据数据库加载完各类元素后,场景画面将如下展示(此处应补充实际画面,如果有)。

或许有人会问:为什么要使用数据库呢?实际上,你可以将游戏的所有数据硬编码在程序中,但当需要增加更多关卡、boss 或资源时,就必须修改程序代码。而采用数据库实现,当需要新增一个关卡时,只需在 scene 表中添加一条记录,说明该关卡以及所需的 boss、资源等信息。这样,开发公司甚至无需亲自动手,只需将添加数据的接口提供给运营公司,运营公司就能持续配置数据,不断丰富游戏内容。

从长远来看,程序与数据分离所带来的优势不言而喻。

作者信息

boke

boke

共发布了 3994 篇文章