Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
来源:互联网 发布:js中的小于等于 编辑:程序博客网 时间:2024/05/20 16:14
Like this post? Follow me on Twitter! There’s been a surprising amount of interest in the post on How To Make a Simple iPhone Game with Cocos2D – and several of you guys have asked for some more in this series! Specifically, some of you asked for a tutorial on how to rotate a turret to face the shooting direction. This is a common requirement for a lot of games – including one of my favorite genres, tower defense! So in this tutorial we’ll cover how do exactly that, and add a rotating turret into the simple game. Special thanks goes to Jason and Robert for suggesting this tutorial! If you have followed along with the last tutorial, you can continue with the project exactly how we left off. If not, just download the code from the last tutorial and let’s start from there. Next, download the new player sprite and projectile sprite images, add them into your project, and delete the old Player.png and Projectile.png from your project. Then modify the lines of code that create each sprite to read as follows: Note that this time, we don’t bother specifying the width and height of our sprites and let Cocos2D handle it for us instead. Compile and run your project, and if all looks well you should see a turret shooting bullets. However, it doesn’t look right because the turret doesn’t rotate to face where it’s shooting – so let’s fix that! Before we can rotate the turret, we first need to store a reference to our Player sprite so we can rotate it later on. Open up HelloWorldScene.h and modify the class to include the following member variable: Then modify the code in the init method that adds the player object to the layer as follows: And finally let’s add the cleanup code in dealloc before we forget: Ok, now that we’ve got a reference to our player object, let’s rotate it! To rotate it, we first need to figure out the angle that we need to rotate it to. To figure this out, think back to high school trigonometry. Remember the mnemonic SOH CAH TOA? That helps us remember that the Tangent of an angle is equal to the Opposite over the Adjacent. This picture helps explain: As shown above, the angle we want to rotate is equal to the arctangent of the Y offset divided by the X offset. However, there are two things we need to keep in mind. First, when we compute arctangent(offY / offX), the result will be in radians, while Cocos2D deals with degrees. Luckily, Cocos2D provides an easy to use conversion macro we can use. Secondly, while we’d normally consider the angle in the picture above positive angle (of around 20°), in Cocos2D rotations are positive going clockwise (not counterclockwise), as shown in the following picture: So to point in the right direction, we’ll need to multiply our result by negative 1. So for exaple, if we multiplied the angle in the picture above by negative 1, we’d get -20°, which would represent a counterclockwise rotation of 20°. Ok enough talk, let’s put it into code! Add the following code inside ccTouchesEnded, right before you call runAction on the projectile: Compile and run the project and the turret should now turn to face the direction it’s shooting! It’s pretty good so far but is a bit odd because the turret just jumps to shoot in a particular direction rather than smoothly flowing. We can fix this, but it will require a little refactoring. First open up HelloWorldScene.h and add the following member variables to your class: Then modify your ccTouchesEnded and add a new method named finishShoot so it looks like the following: That looks like a lot of code, but we actually didn’t change that much – most of it was just some minor refactoring. Here are the changes we made: So let’s give it a shot! Compile and run the project, and the turret should now rotate much more smoothly. First off, here’s the full code for the simple Cocos2D iPhone game that we’ve made so far. Next up in the series is a tutorial on how to add harder monsters and more levels! Or you could always check out my other Cocos2D and Box2D tutorials! Category: iPhoneRotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
Getting Set Up
// In the init methodCCSprite *player = [CCSprite spriteWithFile:@"Player2.png"];// In the ccTouchesEnded methodCCSprite *projectile = [CCSprite spriteWithFile:@"Projectile2.png"];
Rotating To Shoot
CCSprite *_player;
_player = [[CCSprite spriteWithFile:@"Player2.png"] retain];_player.position = ccp(_player.contentSize.width/2, winSize.height/2);[self addChild:_player];
[_player release];_player = nil;
// Determine angle to facefloat angleRadians = atanf((float)offRealY / (float)offRealX);float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);float cocosAngle = -1 * angleDegrees;_player.rotation = cocosAngle;
Rotate Then Shoot
CCSprite *_nextProjectile;
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { if (_nextProjectile != nil) return; // Choose one of the touches to work with UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInView:[touch view]]; location = [[CCDirector sharedDirector] convertToGL:location]; // Set up initial location of projectile CGSize winSize = [[CCDirector sharedDirector] winSize]; _nextProjectile = [[CCSprite spriteWithFile:@"Projectile2.png"] retain]; _nextProjectile.position = ccp(20, winSize.height/2); // Determine offset of location to projectile int offX = location.x - _nextProjectile.position.x; int offY = location.y - _nextProjectile.position.y; // Bail out if we are shooting down or backwards if (offX <= 0) return; // Play a sound! [[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"]; // Determine where we wish to shoot the projectile to int realX = winSize.width + (_nextProjectile.contentSize.width/2); float ratio = (float) offY / (float) offX; int realY = (realX * ratio) + _nextProjectile.position.y; CGPoint realDest = ccp(realX, realY); // Determine the length of how far we're shooting int offRealX = realX - _nextProjectile.position.x; int offRealY = realY - _nextProjectile.position.y; float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY)); float velocity = 480/1; // 480pixels/1sec float realMoveDuration = length/velocity; // Determine angle to face float angleRadians = atanf((float)offRealY / (float)offRealX); float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians); float cocosAngle = -1 * angleDegrees; float rotateSpeed = 0.5 / M_PI; // Would take 0.5 seconds to rotate 0.5 radians, or half a circle float rotateDuration = fabs(angleRadians * rotateSpeed); [_player runAction:[CCSequence actions: [CCRotateTo actionWithDuration:rotateDuration angle:cocosAngle], [CCCallFunc actionWithTarget:self selector:@selector(finishShoot)], nil]]; // Move projectile to actual endpoint [_nextProjectile runAction:[CCSequence actions: [CCMoveTo actionWithDuration:realMoveDuration position:realDest], [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)], nil]]; // Add to projectiles array _nextProjectile.tag = 2; } - (void)finishShoot { // Ok to add now - we've finished rotation! [self addChild:_nextProjectile]; [_projectiles addObject:_nextProjectile]; // Release [_nextProjectile release]; _nextProjectile = nil; }
What’s Next?
- Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
- raywenderlich-Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
- Harder Monsters and More Levels: How To Make A Simple iPhone Game with Cocos2D Part 3
- How To Make A Simple iPhone Game with Cocos2D Tutorial
- How To Make A Simple iPhone Game with Cocos2D Tutorial
- raywenderlich—Harder Monsters and More Levels: How To Make A Simple iPhone Game with Cocos2D Part 3
- [cocos2d 教程转载]How To Make A Simple iPhone Game with Cocos2D Tutorial
- raywenderlich-How To Make A Simple iPhone Game with Cocos2D Tutorial
- How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial
- How To Make a Simple iPhone Game with Flash CS5
- How To Make A Simple Android Game with Cocos2D
- How To Make A Simple Multiplayer Game with Game Center Tutorial: Part 2/2
- How To Make A Simple Multiplayer Game with Game Center Tutorial: Part 1/2
- iphone游戏开发-Collisions and Collectables: How To Make a Tile Based Game with Cocos2D Part 2
- Collisions and Collectables: How To Make a Tile Based Game with Cocos2D Part 2
- How To Make A Side-Scrolling Beat Em Up Game Like Scott Pilgrim with Cocos2D – Part 2
- iphone游戏编程-How To Make a Tile Based Game with Cocos2D
- How To Make a Tile Based Game with Cocos2D
- 设置"添加到QQ表情"右键菜单
- How To Make A Simple iPhone Game with Cocos2D Tutorial
- Windows环境下log4cxx的编译及使用
- android核心模块及相关技术
- Xbox360 Kinect成为“最畅销的消费电子设备“
- Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
- linux内核input子系统解析
- Release 正确 而Debug 挂掉 初始化越界
- -Wl,--no-undefined
- 240多个jQuey插件 http://www.duduwolf.com/
- Cygwin的使用方法
- Harder Monsters and More Levels: How To Make A Simple iPhone Game with Cocos2D Part 3
- 关于SilverLight视频播放器
- map影像地图