Android cocos2d-x开发(四)之如何添加一个精灵和移动一个精灵

1、加入图片资源    如果你运行build_native.sh来编译的话,应该把图片资源加入到Resources文件夹里,否则就把图片文件复制到“assets”文件夹下。

2、添加一个精灵    
   //------------------在场景中添加一个敌人精灵---------start------------------------------ CCSprite *target = CCSprite::spriteWithFile("Target.png", CCRectMake(0, 0, 27, 40));

//determine where to spawn the target along the Y axis
CCSize winSize = CCDirector::sharedDirector()->getWinSize();

int minY = target->getContentSize().height/2;

int maxY = winSize.height - target->getContentSize().height/2;

int rangeY = maxY - minY;

//srand(TimGetTicks);
int actualY = (rand() % rangeY) + minY;

//Create the target slightly off-screen along the right edge,
//and along a random position along the Y axis as calculated
target->setPosition(ccp(winSize.width + (target->getContentSize().width/2), actualY));
          this->addChild(target);
//------------------在场景中添加一个敌人精灵---------end------------------------------       //下面是使精灵移动的代码
     //Determine speed of the target
int minDuration = (int)2.0;
int maxDuration = (int)4.0;

int rangeDuration = maxDuration - minDuration;

//srand(TimGetTicks())
int actualDuration = (rand() % rangeDuration) + minDuration;

//Create the actions
CCFiniteTimeAction* actionMove = CCMoveTo::actionWithDuration((ccTime)actualDuration, ccp(0-target->getContentSize().width/2, actualY));

CCFiniteTimeAction* actionMoveDone = CCCallFuncN::actionWithTarget(this, callfuncN_selector(HelloWorld::spriteMoveFinished));

target->runAction(CCSequence::actions(actionMove, actionMoveDone, NULL));

}

void HelloWorld::gameLogic(ccTime dt)
{
this->addTarget();
}

猜你喜欢

转载自lichunan-d-163-com.iteye.com/blog/1623491