Posted By

saturngod on 12/15/10


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

synced


Scale size by width


 / Published in: Objective C
 

URL: http://www.raywenderlich.com/352/how-to-make-a-simple-iphone-game-with-cocos2d-tutorial

  1. - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  2.  
  3. // Choose one of the touches to work with
  4. UITouch *touch = [touches anyObject];
  5. CGPoint location = [touch locationInView:[touch view]];
  6. location = [[CCDirector sharedDirector] convertToGL:location];
  7.  
  8. // Set up initial location of projectile
  9. CGSize winSize = [[CCDirector sharedDirector] winSize];
  10. CCSprite *projectile = [CCSprite spriteWithFile:@"Projectile.png"
  11. rect:CGRectMake(0, 0, 20, 20)];
  12. projectile.position = ccp(20, winSize.height/2);
  13.  
  14. // Determine offset of location to projectile
  15. int offX = location.x - projectile.position.x;
  16. int offY = location.y - projectile.position.y;
  17.  
  18. // Bail out if we are shooting down or backwards
  19. if (offX <= 0) return;
  20.  
  21. // Ok to add now - we've double checked position
  22. [self addChild:projectile];
  23.  
  24. // Determine where we wish to shoot the projectile to
  25. int realX = winSize.width + (projectile.contentSize.width/2);
  26. float ratio = (float) offY / (float) offX;
  27. int realY = (realX * ratio) + projectile.position.y;
  28. CGPoint realDest = ccp(realX, realY);
  29.  
  30. // Determine the length of how far we're shooting
  31. int offRealX = realX - projectile.position.x;
  32. int offRealY = realY - projectile.position.y;
  33. float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
  34. float velocity = 480/1; // 480pixels/1sec
  35. float realMoveDuration = length/velocity;
  36.  
  37. // Move projectile to actual endpoint
  38. [projectile runAction:[CCSequence actions:
  39. [CCMoveTo actionWithDuration:realMoveDuration position:realDest],
  40. [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
  41. nil]];
  42.  
  43. }

Report this snippet  

You need to login to post a comment.