您的位置:首页 > 移动开发 > Cocos引擎

Cocos2d入门 <四> fire bullet

2013-01-16 16:24 381 查看
我们需要我们的英雄 来发射子弹消灭敌人。

void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
// Choose one of the touches to work with
CCTouch* touch = (CCTouch*)( touches->anyObject() );
CCPoint location = touch->locationInView();
location = CCDirector::sharedDirector()->convertToGL(location);
// Set up initial location of projectile
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCSprite *projectile = CCSprite::create("Projectile.png",  CCRectMake(0, 0, 20, 20));
projectile->setPosition( ccp(20, winSize.height/2) );

// Determinie offset of location to projectile
int offX = location.x - projectile->getPosition().x;
int offY = location.y - projectile->getPosition().y;

// Bail out if we are shooting down or backwards
if (offX <= 0) return;

// Ok to add now - we've double checked position
this->addChild(projectile);
// Determine where we wish to shoot the projectile to
int realX = winSize.width + (projectile->getContentSize().width/2);
float ratio = (float)offY / (float)offX;
int realY = (realX * ratio) + projectile->getPosition().y;
CCPoint realDest = ccp(realX, realY);

// Determine the length of how far we're shooting
int offRealX = realX - projectile->getPosition().x;
int offRealY = realY - projectile->getPosition().y;

float length = sqrtf((offRealX * offRealX) + (offRealY*offRealY));

float velocity = 480/1; // 480pixels/1sec
float realMoveDuration = length/velocity;

// Move projectile to actual endpoint
projectile->runAction( CCSequence::actions(CCMoveTo::create(realMoveDuration, realDest),
CCCallFuncN::create(this,
callfuncN_selector(HelloWorld::spriteMoveFinished)),
NULL) );

}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
  ......
this->setTouchEnabled(true);
// Call game logic about every second
this->schedule( schedule_selector(HelloWorld::gameLogic), 1.0 );

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: