Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
2011-03-10 11:39
671 查看
Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
Like this post? Follow me on Twitter!Let's Rotate This Turret!
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!
Getting Set Up
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:
// In the init method CCSprite *player = [CCSprite spriteWithFile:@"Player2.png"]; // In the ccTouchesEnded method CCSprite *projectile = [CCSprite spriteWithFile:@"Projectile2.png"]; |
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!
Rotating To Shoot
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: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; |
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:
// Determine angle to face float angleRadians = atanf((float)offRealY / (float)offRealX); float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians); float cocosAngle = -1 * angleDegrees; _player.rotation = cocosAngle; |
Rotate Then Shoot
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:
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; } |
We bail at the beginning of the function if there is a value in nextProjectile, which means we’re in the process of shooting.
Before we used a local object named projectile that we added to the scene right away. In this version we create an object in the member variable nextProjectile, but don’t add it until later.
We define the speed at which we want our turret to rotate as half a second for half a circle’s worth of rotation. Remember that a circle has 2 PI radians.
So to calculate how long this particular rotation should take, we multiply the radians we’re moving by the speed.
Then we start up a sequence of actions where we rotate the turret to the correct angle, then call a function to add the projectile to the scene.
So let’s give it a shot! Compile and run the project, and the turret should now rotate much more smoothly.
What’s Next?
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: iPhone
Tags: cocos2D, game, iPhone, sample code, tutorial
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
http://www.raywenderlich.com/692/rotating-turrets
相关文章推荐
- raywenderlich—Harder Monsters and More Levels: How To Make A Simple iPhone Game with Cocos2D Part 3
- Harder Monsters and More Levels: How To Make A Simple iPhone Game with Cocos2D Part 3
- raywenderlich-Rotating Turrets: How To Make A Simple iPhone Game with Cocos2D Part 2
- iphone游戏开发-Collisions and Collectables: How To Make a Tile Based Game with Cocos2D Part 2
- How To Make A Simple iPhone Game with Cocos2D 3.0 Tutorial
- How To Make A Simple WoPhone Game With Cocos2d-x : How To Run Hello World
- How To Make A Side-Scrolling Beat Em Up Game Like Scott Pilgrim with Cocos2D – Part 1
- How To Make A Side-Scrolling Beat Em Up Game Like Scott Pilgrim with Cocos2D – Part 2
- How To Make A Simple Android Game with Cocos2D
- How To Make a Simple iPhone Game with Flash CS5
- How To Make A Simple Multiplayer Game with Game Center Tutorial: Part 2/2
- Collisions and Collectables: How To Make a Tile Based Game with Cocos2D Part 2
- How To Make A Simple Multiplayer Game with Game Center Tutorial: Part 1/2
- How To Create A Mole Whacking Game with Cocos2D: Part 1/2
- How To Create A Mole Whacking Game with Cocos2D: Part 2/2
- Enemies and Combat: How to Create a Tile Based Game with Cocos2D Part 3
- How To Make a Tile Based Game with Cocos2D
- How to make Flappy Bird like game using Cocos2D
- How to Make an iOS VoIP App With Pjsip: Part 2
- How to Make an iOS VoIP App With Pjsip: Part 4