If you're new here, you may want to subscribe to my RSS feed or follow me on Twitter. Thanks for visiting!
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!
(And don’t forget Part 3 in this series – Harder Monsters and More Levels!)
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.jpg and Projectile.jpg 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.jpg"]; // In the ccTouchesEnded method CCSprite *projectile = [CCSprite spriteWithFile:@"Projectile2.jpg"]; |
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!
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; |
Then modify the code in the init method that adds the player object to the layer as follows:
_player = [[CCSprite spriteWithFile:@"Player2.jpg"] retain]; _player.position = ccp(_player.contentSize.width/2, winSize.height/2); [self addChild:_player]; |
And finally let’s add the cleanup code in dealloc before we forget:
[_player release]; _player = nil; |
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:
// 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; |
Compile and run the project and the turret should now turn to face the direction it’s shooting!
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; |
Then modify your ccTouchesEnded and add a new method named finishShoot so it looks like the following:
- (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.jpg"] 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; } |
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:
- 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










héhé again a nice tutoriel :)
i think i’ll be using the rotation movement in my application :)
very good article! will be nice to see more of them coming into this serie… BTW the full code link is broken… thanks!
Very cool tutorial, your site is cached in my NewsFire reader so I can review the tutorial during my breaks/lunch at work. :)
I think the source code link is broken.
Whoops, thanks guys! Links should be fixed now.
Thanks for posting these. It is a great way to see a real foundation for CC. I am so glad to have found your blog!
Very awesome tutorial!!!I was looking for how to do rotation with cocos2D, this fits perfectly for my app
Cool tutorial. Thanks (again).
On a side note: You do not need to retain / release _player. It will be retained by the layer when adding _player as a child.
Looking forward to your next post.
The shooting code up there is rather long and confusing to the average user. Cocos2D is supposed to make things easier not harder. Here’s what the shooting code should look like:
UITouch *myTouch = [touches anyObject];
CGPoint touchPoint = [myTouch locationInView:[myTouch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
[_player runAction:[CCSequence actions:
[CCRotateTo actionWithDuration:1 angle:C_RADIANS_TO_DEGREES(-ccpToAngle(ccpSub(touchPoint, _player.position)))],
[CCCallFunc actionWithTarget:self selector:@selector(finishShoot)],
nil]];
CGPoint moveToPoint = ccpNormalize(ccpSub(touchPoint, _nextProjectile.position));
CGPoint realPoint = ccpAdd(_nextProjectile.position, ccpMult(moveToPoint, 420));
ccTime d = 1;
// Move projectile
[_nextProjectile runAction:[CCSequence actions:
[CCMoveTo actionWithDuration:d position:moveToPoint],
[CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)],
nil]];
// Add to projectiles array
_nextProjectile.tag = 2;
The code works just as good… and much more efficient. Pretty much, I am subtracting the two points, and then adding the two points subtracted and the multiplied value of the two points subtracted together. Then just move it to the point.
Hello Ray. Rotation in this way is made so simple by cocos2d as you described here in this tutorial. But how to rotate an object around a point (or another object) in circular orbits? I am talking about the same motion as it is done by our earth around the sun or by electrons around the nucleus. If you have a way to do this please kindly tell me.
And another interesting thing that I’ve noted while working on my game is about rotating a layer. When you rotate layer, screen positions are also rotated.
I’ve a layer of target balls arranged in 9 rows in a diamond shape. I rotate this layer to 180 degrees when my fireBall collides with them. Now bottom row has apparently become the top row and vice versa, but it is strange to see when I hit my fireBall again to (the apparent) bottom row, it actually moves to the top row(which was in fact bottom row before layer rotation).
I’m getting crazy with such strange results but I wish that there be a simple thing missed by me in code because this simple rotation of layer did everything I needed except the above mentioned problem.
That was a great tutorial!
Can’t wait for you to show how to make more difficult monsters! I have tried for too long to make my enemies deal with more then one shot, but the game randomly gives them lives between 1 and the wanted value, and not the exact wanted value =/
Like I said, can’t wait :D
You rock!!!
Also maybe some very simple AI from the enemies, perhaps a boss?
@Atif There’s an easy way to rotate your sprite around a point, just move the anchor point outside of the sprite (instead of the default position at the center of the sprite (0.5,0.5)). As documentation says : anchorPoint is the point around which all transformations and positioning manipulations take place. It’s like a pin in the node where it is “attached” to its parent.
For example, you can try something like this :
CCSprite *ninja = [CCSprite spriteWithFile:@"Player.jpg"];
ninja.position = ccp(240,160);
ninja.anchorPoint = ccp (-1,0);
[ninja runAction: [CCRepeatForever actionWithAction:[CCRotateBy actionWithDuration:2 angle:360]]];
[self addChild:ninja];
But moving the anchor has also consequences on positioning, so be careful !
@Caleb – Cool I actually wasn’t aware of those convenience functions in Cocos2D, that combined with your method of just having the objects shoot at a set direction offscreen each time does indeed make things simpler. I’ll start using those in future tutorials, thanks for sharing!
@Atif/Eric – Eric is correct. You may also find it useful to make one sprite a child of another, i.e. make the moon a child of a planet. That way when you rotate the planet around the sun, the moon will also rotate (and you can rotate that around the planet as it is rotating). For a good example, check out cocosnodeTest in the cocos2D samples – the anchorPoint and children case.
@MrLucky – Thanks for the ideas!
I’d love to see you continue the series. It’s been a big help to me since I’m such a newb to writing games (although I have many years experience writing software). I was so lost, but I am finally starting to get my head around it thanks to these articles. Good job!
Hi Ray – Thanks so much for adding to your Cocos2D game tutorial and also for the clarity in your explanations. I have pretty decent iPhone SDK skills, but was lost when I tried to get into using Cocos2D. I am almost ready to attempt the game build I have been kicking around thanks to you!
Also, I found this tutorial on how to add a online leaderboard to your iPhone game. Hope it helps someone. http://icodeblog.com/2009/10/29/iphone-coding-tutorial-creating-an-online-leaderboard-for-your-games/
In addition to Cocos2D, I found there is an emerging game framework called Sparrow http://www.sparrow-framework.org/ – this is geared toward Flash Actionscript coders. Not sure how good it is. It would be interesting to see a comparison game tutorial in this framework.
Thanks Eric and Ray. Making one CCNode child of another CCNode makes the rotation around parent easy. But here again same problem arises that I pointed in my last post about layer rotation that when parent (doesn’t matter layer or sprite) is rotated, all child nodes also rotate but only apparently. If I want to get new positions of child nodes, I can’t. It looks as if screen has rotated, not the sprites… Floor goes to top and ceiling comes at the bottom. Child’s “position values” are not according to the rotation but they possess same position values as they had before rotation… CC_HONOR_PARENT_TRANSFORM also doesn’t work . If you know a way to get new positions of child nodes after rotation of parent please let me know too. Thanks for your help and sorry for my bad & broken English.
Great tutorial!
Looking forward to your next tutorial with more difficult monsters and multiple levels. That will really help my game a lot :)
@Atif You’re right, when you rotate a layer, layer’s childs keep their position value in this layer unchanged and it’s normal, their position inside the layer hasn’t changed, only the orientation of the layer. If you want to obtain the position of childs from your point of view (what you see on screen), you will have to convert their positions using the CCNode function :
- (CGPoint) convertToWorldSpace:(CGPoint)nodePoint
For example, try this code in the init function of the HelloWordScene :
CCColorLayer *bgLayer = [CCColorLayer layerWithColor:ccc4(255, 255, 255, 255)];
[self addChild:bgLayer];
CCLayer *parentLayer = [[CCLayer alloc] init];
parentLayer.rotation = 180;
[self addChild:parentLayer];
[parentLayer release];
CCSprite *ninja = [CCSprite spriteWithFile:@"Player.jpg"];
ninja.position = ccp(240,200);
[parentLayer addChild:ninja];
NSLog(@”Position in layer: (%f,%f)”,ninja.position.x,ninja.position.y); //(240,200)
CGPoint ninjaPos = [parentLayer convertToWorldSpace:ninja.position];
NSLog(@”Position in ‘real world’: (%f,%f)”,ninjaPos.x,ninjaPos.y); // (240,120)
and you have the opposite function that converts from global to local, and special ones for dealing with touch, see in CCNode class documentation.
Hope it helps !
Awesome tutorial :)
I am constantly checking your page for your next tutorial on difficult monsters, etc. I am a newb and this is exactly what my game needs :) Ur the best!
Great tutorial! One thing that I have been trying to figure out is once you have changed the original position of your player and the projectile, how can you shoot up, down, or backwards? You have set it up so that if you touch up, down, or backwards it bails out and does not shoot, but is there any way to make it shoot up, down, and backwards? Thanks for your help.
@Eric. Thanks. Your help has done a lot for me. BTW I found you at http://johnehartzog.com too.
I am very pleased to see that senior developers like you and Mr. Ray Wenderlich are keen to help juniors like me. Thanks again to both of you.
@Eric: Thanks for helping out here!
@Cameron: Actually this is quite easy if you use the Cocos2D helper functions suggested by Caleb in the comments above. To help you out with this, I’ve modified the source code project for this tutorial to move the turret more toward the middle and to use the Cocos2D helper functions Caleb suggested to allow shooting in any direction. Download the updated project and check it out, hope it helps!
@Atif You’re welcome but I’m not this Eric, I would be proud to be the developer of StickWars but I’m just a poor french developer that develops a game and loves Cocos2D :p
@Rey it’s always a pleasure to help !
Now that you have moved the player and allowed him to shoot in every direction, it could be fun that monsters try to rush on the player coming from everywhere and you lose one life every time they hit you. In addition to your other suggestions, you could have bonus items that move fast across the screen, if you hit them, they can give you : more powerful weapons, extra life, possibility to slow monsters during a certain amount of time, etc.
@Eric
Yeah, thats a great idea :)
Hi Ray,
Just trying to understand the two CCSequence actions you create. You create an action to rotate the turret, and then immediately create a sequence of actions to move the _nextProjectile. Does the _nextProjectile action get executed immediately, i.e. the projectile starts its movement action before the turret rotates, but you only get to see the projectile once the projectile is added as a child in finishShoot?
Regards
i
@Indy: AFAIK, the action only begins executing once the sprite is added into the scene, so we can set up the actions in advance for convenience sake like we did here.
hi
iv been giving the new shooting code a try and have come across a problem, when shooting in the range of 0 degrees to 180 the turret moves lightning fast but the further away from 0 you get the slower it gets till it you shoot at 359 degrees it takes ages to move there. is there a simple work around to get the turret to rotate at a constant speed?
thanks
@Darc_pyro: Good catch! Looks like I wasn’t handling the rotation speed calculation right – I was basing it on the angle the turret was rotating to rather than the difference between the current angle and the target angle.
I’ve updated the sample project with new code that should fix the problem. Thanks for letting me know!
Hi Ray,
Thanks. So its only the action of addChild which starts any queued actions? Is it possible for you to queue several actions up and have them all execute when added…i.e. a rotate action happening while a CCMoveTo is happening?
Thanks
i
@indy – I looked into the code a bit, and it looks like it’s working as I suspected.
1) When you call runAction, it calls addAction on CCActionManager, setting the paused variable to true if the node is not running. And before a node is added to a scene, it’s not running, so the actions should be paused.
2) When you call addChild, it calls onEnter on each child node, which calls activateTimers, which calls resumeAllActions on the CCActionManager, which gets the actions running.
So yeah you could combine multiple actions in advance if you would like (such as using a CCSequence) if you’d like just the same way.
Thanks Ray,
Whereas a CCSequence is one action after another, can you run multiple actions simultaneously.
Regards
i
Ah yes, there’s a CCSpawn action you can use for that.
Hi,
great articles! I´d really love to see this continued! Wonderful intro to Cocos2D. Really comprehensive!
Thanks,
Marco
Another awesome tutorial. Thanks, Ray :).
good articles, thank you Ray.
You’ve been such a massive help for me Ray, all of these tutorials are brilliant I just hope you can keep going!
One thing I noticed, don’t you need to release the projectile if the ccTouchesEnded function is bailed out by an out of range touch?
if (offX <= 0) {
[_nextProjectile release];
_nextProjectile = nil;
return;
}
@John: You are indeed correct, nice catch!
Hi Ray,
I have been following your tutorials and they are really helping me learn cocos2d and iphone game development. I was wondering if you are planning on doing a more detailed tutorial on loading different levels as I really struggling with this aspect.
Thanks
@Stephen: Have you seen this tutorial yet?
http://www.raywenderlich.com/782/harder-monsters-and-more-levels
hi Ray
First of all i would like to thank you for writing such wonderful articles. U Rock!!
I have a question for you.
I want to make a object fall with a “parachute effect”. ie. it sways as it falls down.
how can i achieve this??Could you point me to the right direction.
Thanks
Can anyone help me?
After I code and use your project nothing happen, it shows logo of cocos2d and stay still like that. I don’t know what show I do?
@Bk: Hm… you ask good questions :] I’d imagine you’d want to use a sequence of CCBezier actions to get a nice swing arc going back and forth. See ActionsTest that comes with Cocos2D for an example of using CCBezier.
@Warchief: When that happens usually it means there’s some kind of error in the init method. Did you try downloading the sample project and comparing your code to that, or debugging through your init method?
Hi Ray. I am new to iphone programing and games programing… i really like your tutorials… they are giving me great start for some types of games… i just wanted to say Thanks
@Ray
I had tried using CCBezier but the fall dint look elegant enough. Guess i will have to go back and fine tune it.
Thanks
Thank god u find the questions good, cos ppl usually don reply to lame questions. :P
how could i make it so that i need to touch the screen and the turret follows my finger?
@spoolup: For an example of that, check out the Tom the Turret sample project that Steve Oldmeadow and I wrote:
http://www.raywenderlich.com/1345/tom-the-turret
Hi Ray,
Love the Tom the Turret tutorial, especially the health bars. My only issue with it was if you Box2D Debug Draw enabled, the Tom the Turret example doesn’t reset the OpenGL state (line thickness) and so I got some very interesting edges to everything!!
Regards
i
thanks Ray!
i downloaded and tried building… i get
Invalid value ‘coop.plausible.blocks.compilers.gcc.4_2′ for GCC_VERSION
disregard…. blonde mooment :)
forgot to set the build version…
looks good, but what i was after was keeping my finger pressed on the screen and the turret following my finger. then once the finger is lifted the projectile is shot :(
@Warchief : I was having the same problem, until I did a little reorganization of the init method. Now my init method looks like this
-(id) init
{
if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {
CGSize winSize = [[CCDirector sharedDirector] winSize];
self.isTouchEnabled = YES;
_targets = [[NSMutableArray alloc] init];
_projectiles = [[NSMutableArray alloc] init];
_player = [[CCSprite spriteWithFile:@"Player.jpg"] retain];
_player.position = ccp(_player.contentSize.width/2, winSize.height/2);
[self addChild:_player];
//[self addChild:player];
[self schedule:@selector(gameLogic:) interval:1.0];
[self schedule:@selector(update:)];
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"background-music-aac.caf"];
}
return self;
}
I think the problem was that I was making sprites before I had touch enabled and had any info about screen size. So, I brought those two lines to the top and now the game is working fine :)
Ray, you are a good guy. thank you for all these tutorials! It helps a lot
Hi Ray,
You have written excellent tutorials.It would be great if you can explain how to handle Menus .On a start screen that provides with Menu Items start and exit application before this scenes start.This will make a complete tutorial on Cocas 2d and it is appreciated if you get some time to explain that also.
I like your tutorials very much.
@indy: Whoops, nice catch! :] By the way, I see you everywhere in forum search results lately haha looks like you are quite busy :]
@spoolup: You can do that – probably the best thing to do is to put the code that rotates the turret in ccTouchMoved so it tracks your finger, and have ccTouchEnded actually fire the shot.
@Ahmad: Thanks for helping out @Warchief!
@Alyoo: Thanks for the kind words, I’m really glad you find the tuts helpful :]
@uday: Thank you also, and plus for the suggestion! As far as how to use Menus, it’s not exactly what you’re looking for, but this post actually covers a little bit about how you can use menus that might help:
http://www.raywenderlich.com/414/how-to-create-buttons-in-cocos2d-simple-radio-and-toggle
hi ray
i want to plung the ball using slingshot
any idea about that
@srinivas: For a slingshot effect, you could make the ball move in an arc using CCBezierTo, or you could use a physics engine such as Box2D or Cocos2D.
Hi RAY
in the sample code that u have given in the end what does gameconfig and rootviewcontroller files do??
Mayukh
The rotation code in the current sample code works, but is misleading:
CGFloat rotateSpeed = 0.5 / 180; // Would take 0.5 seconds to rotate half a circle
CGFloat rotateDuration = fabs(rotateDiff * rotateSpeed);
You’re multiplying by an inverse speed instead of dividing by a speed. This does the same thing and makes more sense:
CGFloat rotateSpeed = 360; // degrees per second
CGFloat rotateDuration = fabs(rotateDiff / rotateSpeed);
Great tutorials – thanks!
@mayukh: GameConfig: File with configuration options for Cocos2D, comes by default in newer Cocos2D templates. RootViewController: The view controller containing the OpenGL view, which Cocos2D resides within, also comes by default in newer Cocos2D templates.
@Tommy: Thanks, you’re right that is more clear – I’ve updated the sample project to use your suggested method. Thanks again!
Hi Ray thanks for your nice tuitorial.I learned a lot from this.Can you help me in the follwing topic- http://stackoverflow.com/questions/4296542/how-to-keep-fps-rate-constant-in-cocos2d
thanks ray it is again a nice tutorial
@sazzad: I took a brief look at your question. It seems like your problem is due to continuously allocating/deallocating sprites. A common solution is to reuse a pre-allocated buffer of Sprites. I.e. create 100 sprites at start, and keep track of which ones are currently in use and which aren’t, rather than continuously allocating sprites when needed.
@Manoj: Thanks!
Hi Ray,
The images are rectangles and we move them on white background its ok.If we use the same images with different background color than rectangles can be seen as background color is no longer white.How can we get rid of this problem what should i do to make only object to appear on any background.
I am a beginner and your help is appreciated.
Hi Ray,
I was wondering how to initialize a sprite already rotated by an angle. I mean I use box2d and I have a box body and I set angle to that body. Later I wanted to add a sprite to it but I couldnt arrange angle for sprite.
If someone can help me out, I ll be glad.
Thak you
Omer Faruk
@uday: Make sure your images are saved as PNGs with transparent regions for the backgrounds (not white).
@Omer: As long as you have your update loop setting the sprite’s position and angle to the same position/angle as the Box2D body, it should be OK.
Hi everyone;
here is the code that i stuck with i couldnt figure out what is wrong. i have a function and i pass it a fixture pointer reference to add sprite on to that fixture’s body. but when i run it the body shape on the screen stays as 45 degree of angle but the sprite stands like no rotation effected it.
-(void)boards_setSpriteSheetswithFixture:(b2Fixture*&)fixture size:(int)size
{
CCSprite *board = [CCSprite spriteWithFile:[NSString stringWithFormat:@"board%i.jpg", size]];
fixture->GetBody()->SetUserData(board);
b2Vec2 pos = fixture->GetBody()->GetPosition();
board.position = CGPointMake(pos.x*PTM_RATIO, pos.y*PTM_RATIO);
board.rotation = -1 * CC_RADIANS_TO_DEGREES(fixture->GetBody()->GetAngle());
[self addChild:board];
}
if anyone knows how to solve this please help me.. i spent hours fir this little thing..
Thank you.
awesome tutorial series. Like this very much