cocos2d tiledmap

#include "HelloWorldScene.h"

USING_NS_CC;

CCScene* HelloWorld::scene()
{
    CCScene *scene = CCScene::create();
    HelloWorld *layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}


bool HelloWorld::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
    
    //添加地图
    map=CCTMXTiledMap::create("map.tmx");
    addChild(map);

    //获取英雄的对象层
    CCTMXObjectGroup *objGroup=map->objectGroupNamed("objHero");
    CCDictionary *hero=objGroup->objectNamed("hero");
    float x=hero->valueForKey("x")->floatValue();
    float y=hero->valueForKey("y")->floatValue();

    sp=CCSprite::create("1.png");
    sp->setAnchorPoint(CCPointZero);//瓦片地图默认放在左下角。所以需要设置一下。
    sp->setPosition(ccp(x,y));
    addChild(sp);

    //打开触屏开关
    this->setTouchEnabled(true);
    
    return true;
}

CCPoint HelloWorld::tileCoordForPosition(CCPoint position)
{
    int x = position.x /map->getTileSize().width;
    int y = ((map->getMapSize().height * map->getTileSize().height) - position.y) / map->getTileSize().height;
    return ccp(x, y);
}

void HelloWorld::ccTouchesBegan(CCSet *pTouches,CCEvent *pEvent)
{
    CCTouch* touch=(CCTouch*)(pTouches->anyObject());
    CCPoint pos=touch->getLocation();
    CCActionInstant *func=CCCallFunc::create(this,callfunc_selector(HelloWorld::judgeCollide));
    sp->runAction(CCSequence::create(CCMoveTo::create(1,pos),func,NULL));
}

void HelloWorld::judgeCollide()
{
    CCTMXLayer *collisionLayer=map->layerNamed("collisionLayer");
    CCPoint tiledPos=tileCoordForPosition(sp->getPosition());
    if(collisionLayer->tileGIDAt(tiledPos))
    {
        CCLOG("%d",collisionLayer->tileGIDAt(tiledPos));
        collisionLayer->removeTileAt(tiledPos);
    }
}


void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
    CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}

 

posted @ 2014-05-19 06:26  yufenghou  阅读(475)  评论(0编辑  收藏  举报