Chapter 4 - How to Fire some Bullets

Now, we want to let the hero fire some bullets to kill the enemies, add the codes below to set the layer touch-enabled.

1// cpp with cocos2d-x

2this->setTouchEnabled(true); or this->setIsTouchEnabled(true);

Then we could receive the touch event now.
Declare the callback function "void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);" in HelloWorldScene.h, and implement the function in HelloWorldScene.cpp.

 1// cpp with cocos2d-x

 2void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)

 3{

 4    // Choose one of the touches to work with

 5    CCTouch* touch = (CCTouch*)( touches->anyObject() );

 6    CCPoint location = touch->locationInView();

 7    location = CCDirector::sharedDirector()->convertToGL(location);

 8

 9    // Set up initial location of projectile

10    CCSize winSize = CCDirector::sharedDirector()->getWinSize();

11    CCSprite *projectile = CCSprite::create("Projectile.png", 

12        CCRectMake(0, 0, 20, 20));

13    projectile->setPosition( ccp(20, winSize.height/2) );

14

15    // Determinie offset of location to projectile

16    int offX = location.x - projectile->getPosition().x;

17    int offY = location.y - projectile->getPosition().y;

18

19    // Bail out if we are shooting down or backwards

20    if (offX <= 0) return;

21

22    // Ok to add now - we've double checked position

23    this->addChild(projectile);

24

25    // Determine where we wish to shoot the projectile to

26    int realX = winSize.width

27                         + (projectile->getContentSize().width/2);

28    float ratio = (float)offY / (float)offX;

29    int realY = (realX * ratio) + projectile->getPosition().y;

30    CCPoint realDest = ccp(realX, realY);

31

32    // Determine the length of how far we're shooting

33    int offRealX = realX - projectile->getPosition().x;

34    int offRealY = realY - projectile->getPosition().y;

35    float length = sqrtf((offRealX * offRealX) 

36                                        + (offRealY*offRealY));

37    float velocity = 480/1; // 480pixels/1sec

38    float realMoveDuration = length/velocity;

39

40    // Move projectile to actual endpoint

41    projectile->runAction( CCSequence::create(

42        CCMoveTo::create(realMoveDuration, realDest),

43        CCCallFuncN::create(this, 

44

45        callfuncN_selector(HelloWorld::spriteMoveFinished)), 

46        NULL) );

47}

Ok, build and run, touch the screen(on the emulator? click the screen!), and enjoy the effect.
PS: To keep identical with the Object-C codes, there would be some warnings of conversion from 'float' to 'int', don't care about them.

Win32 Chapter 4 - How to Fire some Bullets

你可能感兴趣的:(apt)