为图层上的N多怪物创建站立时的动画

来源:互联网 发布:串行12864接单片机 编辑:程序博客网 时间:2024/05/02 02:01

说在前面的话:

怪物在地图上的位置是不变的,但它们都有对应的原地站立时的动画。大家可能会对这些怪物分别创建动画。这样做没错,但是想想就觉得麻烦:如果有100种怪物的话,难道要定义100个动画模板吗?答案是否定的。可以参考下testcpp下的TMXReadWriteTest例子。


有DEMO下载。


看代码:

#pragma once#include "cocos2d.h"class Enemy : public cocos2d::CCObject{public:Enemy(void);~Enemy(void);// 怪物在TileMap上的位置cocos2d::CCPoint position;// 怪物初始的图块IDint startGid;};

class HelloWorld : public cocos2d::CCLayer{private:cocos2d::CCTMXTiledMap* m_pTiledMap;cocos2d::CCArray* m_pEnemyAry;cocos2d::CCTMXLayer* m_pEnemyLayer;private:void updateEnemyAnimation(float dt);public:HelloWorld() {m_pTiledMap = NULL;m_pEnemyAry = NULL;m_pEnemyLayer = NULL;}~HelloWorld() {}    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone    virtual bool init();      // there's no 'id' in cpp, so we recommand to return the exactly class pointer    static cocos2d::CCScene* scene();        // a selector callback    void menuCloseCallback(CCObject* pSender);    // implement the "static node()" method manually    CREATE_FUNC(HelloWorld);};#endif  // __HELLOWORLD_SCENE_H__

bool HelloWorld::init(){    bool bRet = false;    do     {        CC_BREAK_IF(! CCLayer::init());m_pTiledMap = CCTMXTiledMap::create("map_01.tmx");this->addChild(m_pTiledMap);m_pEnemyAry = CCArray::create();m_pEnemyAry->retain();m_pEnemyLayer = m_pTiledMap->layerNamed("enemy");CCSize s = m_pEnemyLayer->getLayerSize();for (int i = 0; i < s.width; i++) {for (int j = 0; j < s.height; j++) {// 位置对应的图块IDint gid = m_pEnemyLayer->tileGIDAt(ccp(i, j));if (gid != 0) {Enemy* enemy = new Enemy();if (enemy)enemy->autorelease();else {CC_SAFE_DELETE(enemy);continue;}enemy->position = ccp(i, j);enemy->startGid = gid;m_pEnemyAry->addObject(enemy);}}}this->schedule(schedule_selector(HelloWorld::updateEnemyAnimation), 0.2F);        bRet = true;    } while (0);    return bRet;}
// 更新图块位置的动画void HelloWorld::updateEnemyAnimation(float dt) {CCObject* obj = NULL;Enemy* enemy = NULL;CCARRAY_FOREACH(m_pEnemyAry, obj) {enemy = (Enemy*) obj;if (enemy != NULL) {// 获取指定位置的图块IDint gid = m_pEnemyLayer->tileGIDAt(enemy->position);// 如果指定位置没有图块则执行下一次循环if (gid == 0)continue;gid++;if ((gid - enemy->startGid) > 3)gid = enemy->startGid;// 在指定位置上设置新的图块IDm_pEnemyLayer->setTileGID(gid, enemy->position);}}}


原创粉丝点击