環境
使用ツール
Tiled Map Editor (ver 0.9.1)
やりたいこと
tiledで作成した情報を元にマップ上にオブジェクトの配置
極力わかりやすく、汎用的に…書いたつもり
ソース
TMXTiledMap
はすでに配置済みの状態
その後にこのメソッドを呼び出す感じでtiledからの初期配置が可能
GameScene.cpp
void GameScene::setAllMapObject()
{
// マップ取得
auto tiledMap = (TMXTiledMap *)this->getChildByTag(TAG_MAP);
// object group取得
auto objectGroup = tiledMap->getObjectGroup("objects");
// その中から全objectの取得
auto objects = objectGroup->getObjects();
if (objects.empty()) {
log("can not find object");
return;
}
// 取得したオブジェクトの情報を元に実際にマップ上へセットしていく
for (auto object : objects) {
// objectに設定されているプロパティなどを取得
ValueMap objectInfo = object.asValueMap();
if (objectInfo.find("name") == objectInfo.end() || objectInfo.find("type") == objectInfo.end()) {
log("can not find necessary info");
continue;
}
auto name = objectInfo.at("name").asString(); // 同タイプでobjectを判別するために一意の値を設定するようにする(今は未使用)
auto type = objectInfo.at("type").asString(); // objectのタイプ
Node* obj = NULL;
// 独自クラスもってるならそれを設定する(今回はPlayerクラス)
if (type == "Player") {
obj = Player::create();
}
// 独自クラスを持ってない汎用クラスの場合
else if (type == "Sprite") {
obj = Sprite::create(objectInfo.at("file").asString());
} else if (type == "LayerColor") {
obj = LayerColor::create(Color4B(objectInfo.at("r").asInt(), objectInfo.at("g").asInt(), objectInfo.at("b").asInt(), objectInfo.at("a").asInt()), objectInfo.at("width").asFloat(), objectInfo.at("height").asFloat());
// ほかタイプとまとめて位置調整するために調整
obj->ignoreAnchorPointForPosition(false);
obj->setAnchorPoint(Point::ANCHOR_MIDDLE);
} else {
log("unknown type");
continue;
}
// 表示・非表示
obj->setVisible(objectInfo.at("visible").asString() == "1");
// 表示位置(マップのタイルの中心にくるように)
auto tileSize = tiledMap->getTileSize();
// 取れる位置は左下起点なので調整
auto x = objectInfo.at("x").asFloat() + tileSize.width * 0.5;
auto y = objectInfo.at("y").asFloat() + tileSize.height * 0.5;
obj->setPosition(Point(x, y));
// 配置
tiledMap->addChild(obj);
}
}
Tile Map Editor の設定
素材
今回コチラの素材を利用しております
ぴぽや倉庫
参考WEB
Cocos2D 2.Xでタイルベースゲームの作成チュートリアル
cocos2dの話だけどそこは自分で脳内置換で。
最初から丁寧に書かれてるので導入としては完璧
全2ステップ
メモ・感想
Objectのプロパティは自由に設定できてコードで取得できるので
もっといろいろ拡張できそう…けど
多分それぞれで独自クラス(今回で言えばPlayerクラス)作ってやるだろうから、
その中であれこれするのが普通なのかな
多分自分でもそうするので、今回書いた汎用クラスのケースはほぼないかも(笑)
何かアレばコメントなりtwitterなりで押してくださいな