I’m just getting started with Cocos2d-x and Tiled, and I’m stuck trying to get the x and y values of my playerSpawn object that I defined in the objects layer in Tiled. I want to use them to set the position of the player.
Yes. I have read the guide. But the information on tiled maps is very brief. There is no sample code on how to get the coordinates of an object in the map.
In Tiled, you have different kinds of layers. One type of layer is used for placing tiles (tile layer), another type of layer (object layer) is used for placing ‘regions’. This could be 1, or a bunch of tiles. The interesting thing is that you can name that region and then refer to it from your code.
Thanks for pointing me to the cpp-tests. I wouldn’t have thought of checking those for information.
And I would love to help … but : what’s a PR and how do I send one ?
What type is your map? Ortho, Iso?
Your asInt error should only occur if you have a “null” object. You can check Value for null using isNull().
// Our Isometric map code to get region in tile-space
// rect in tile coords (w == 2 => region of 2 tile width)
Rect STMap::tileRectFromObject(const ValueMap& object)
{
float tileHeight = this->getTileSize().height;
auto group = this->getObjectGroup(groupName);
// if(group) {
auto obj = tileGroup->getObject(tileId);
// if(! obj.empty()) {
auto objType = obj.at("type").asString();
auto objName = obj.at("name").asString();
// size of region/object in points
float height = object.at("height").asFloat();
float width = object.at("width").asFloat();
// one could acquire value asInt() instead, but float makes sense
// since Tiled exports as floats (you can position between tile coords
float xOff = object.at("x").asFloat();
float yOff = object.at("y").asFloat();
height = height / tileHeight - 1.f;
width = width / tileHeight - 1.f;
xOff = xOff / tileHeight;
// y is coord top-down instead of bottom-up (or vice versa)
yOff = this->getMapSize().height - yOff / tileHeight - (height + 1.f);
//dlog2("room object: %s, %.2f,%.2f,%.2f,%.2f", roomName.c_str(), height,width,xOff,yOff);
return Rect(floorf(xOff), floorf(yOff), floorf(width), floorf(height));
}