cocos2dx TMX地图

前端之家收集整理的这篇文章主要介绍了cocos2dx TMX地图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
auto map = TMXTiledMap::create("map.tmx");  //加载地图

    auto mapSize = map->getMapSize();  //获取地图大小

    this->addChild(map);    //添加到当前

    auto mapProperties = map->getProperties(); //获取地图属性

    CCLOG("%s",mapProperties["type"].asString().c_str());  //获取type

    auto sceneLayer = map->getLayer("scene");   //获取图层scene

    auto layerProperties = sceneLayer->getProperties();  //获取图层信息

    CCLOG("%s",layerProperties["type"].asString().c_str());

    auto tileProperties = map->getPropertiesForGID(1).asValueMap();  //获取第一个图块的信息

    CCLOG("%s",tileProperties["type"].asString().c_str());

    auto objectGroup = map->getObjectGroup("object");   //获取object对象的对象组

    auto objectPlayer = objectGroup->getObject("player"); //获取player对象

    CCLOG("%s",objectPlayer["type"].asString().c_str());

    auto objectColor = objectGroup->getObject("color"); //获取color对象

    auto colorX = objectColor["x"].asInt() / 32;
    auto colorY = objectColor["y"].asInt() / 32;
    auto colorW = objectColor["width"].asInt() / 32;
    auto colorH = objectColor["height"].asInt() / 32;

    for (int i = colorX; i < colorX + colorW; i++){
        for (int k = colorY; k < colorY + colorH; k++){

            auto sprite = sceneLayer->getTileAt(Vec2(i,mapSize.height - k - 1));  //获取瓦块

            sprite->setColor(Color3B(255,0,0)); //修改瓦块

        }
    }

    auto player = Sprite::create("c.png");

    player->setPosition(objectPlayer["x"].asFloat(),objectPlayer["y"].asFloat());

    this->addChild(player);

    auto listener = EventListenerTouchOneByOne::create();  //

    listener->onTouchBegan = [player](Touch *touch,Event* event){

        auto target = (TMXTiledMap*)event->getCurrentTarget();

        auto sceneLayer = target->getLayer("scene");

        auto point = target->convertToNodeSpace(touch->getLocation()); //世界坐标转map本地坐标

        point.x = int(point.x / 32);
        point.y = target->getMapSize().height - int(point.y / 32) - 1;


        auto tileGID = sceneLayer->getTileGIDAt(point);  //获取瓦块的GID

        auto tile = target->getPropertiesForGID(tileGID).asValueMap();  //获取图块信息

        if (tile["move"].isNull() != true && tile["move"].asBool() == true){  //判断是否可以移动
            player->setPosition(target->convertToNodeSpace(touch->getLocation()));
        }
        return false;
    };

    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,map);

猜你在找的Cocos2d-x相关文章