加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2dx TMX地图

发布时间:2020-12-14 16:57:03 所属栏目:百科 来源:网络整理
导读:auto map = TMXTiledMap::create( "map.tmx" ); //加载地图 auto mapSize = map -getMapSize(); //获取地图大小 this -addChild( map ); //添加到当前 auto mapProperties = map -getProperties(); //获取地图属性 CCLOG( "%s" ,mapProperties[ "type" ].asS
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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读