cocos2d sprite collision detection boundingbox - iphone

I got 2 sprites. I use the boundingbox to check for collision with CGRectIntersectsRect. But it is not working.
HBBall and HBpaddle has a CCSprite called image.
Init:
ball = [[HBBall alloc] init];
ball.position = ccp(150, 50);
[self addChild:ball];
[update addObject:ball];
paddle1 = [[HBPaddle alloc] init];
paddle1.position = ccp(50, 160);
[self addChild:paddle1];
Update:
if (CGRectIntersectsRect([paddle1.image boundingBox], [ball.image boundingBox]))
CCLOG(#"ball hit paddle");
CGRectIntersectsRect retuns always true. Does anyone have an idea?

you cant pass directly the bounding box, because it's relative to the sprite. You MUST pass the absolute CGRect boundingbox like this:
s = CCsprite
s.anchorPoint = ccp(0, 0);
CGRect absoluteBox = CGRectMake(s.position.x, s.position.y, [s boundingBox].size.width, [s boundingBox].size.height);
make necessary adjustments!
hope can help!

http://www.iphonedevsdk.com/forum/iphone-sdk-game-development/17082-cocos2d-collision-detection-between-sprites.html ? Have you googled? This seems like it would be a pretty basic issue in the cocos2d framework.

Related

Emitted particles follow parent node

I am setting up an SKNode as follows:
- (id)init {
self = [super init];
if (self) {
SKTextureAtlas *atlas = [SKTextureAtlas atlasNamed:#"Sprites"];
SKSpriteNode *spriteNode = [SKSpriteNode spriteNodeWithTexture:[atlas textureNamed:#"Cat"]];
[self addChild:spriteNode];
// Create particle trail
SKEmitterNode *emitterNode = [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:#"Hearts" ofType:#"sks"]];
emitterNode.position = CGPointMake(0, 20);
[self insertChild:emitterNode atIndex:0];
// Setting up the physics
self.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:spriteNode.frame.size];
self.physicsBody.dynamic = YES;
self.physicsBody.affectedByGravity = NO;
}
return self;
}
When this node moves around horizontally along the X-axis, the source of the particle trail moves along with it, which is expected. What is not expected is that emitted particles do this as well, when instead I expect them to move straight up along the Y-axis from their original X position.
Is there a way to prevent this behaviour?
Creation (in scene):
SPAPlayer *player = [[SPAPlayer alloc] init];
player.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:player];
Movement code:
[node.physicsBody applyForce:CGVectorMake(20 * data.acceleration.x, 0)];
Image for reference:
Make the emitter a child of the sprite (as you already have).
To make the particles move independently from where the player node is, assign the SKEmitterNode's targetNode property, preferably assign it the scene as in:
// be sure self.scene isn't still nil when you do this, for instance in node's init
emitter.targetNode = self.scene;
This will spawn the particles at the player sprite position but they won't travel along with it.

Setting frame of CCTexture to fit into a predefined frame CCSprite

I am downloading an image from server and displaying it on game scene. I am able to get the CCTexture2D of the image from server and display it on game scene. The problem is that the image from server may vary in size. But I have to display that image on to a predefined frame CCSprite.
CCSprite *temp = [CCSprite spriteWithTexture:[[CCTexture2D alloc] initWithImage:[UIImage imageWithData:data] resolutionType:kCCResolutioniPhoneFourInchDisplay]];
CCRenderTexture *test=[CCRenderTexture renderTextureWithWidth:70 height:70]; //set proper width and height
[test begin];
[temp draw];
[test end];
UIImage *img=[test getUIImageFromBuffer];
sprite_Temp =[CCSprite spriteWithCGImage:img.CGImage key:#"1"];
sprite_Temp.tag = K_TagUserImage;
sprite_Temp.scale=1;
sprite_Temp.position=ccp(432,273);
[self addChild:sprite_Temp z:1];
I am using this code to resize the CCTexture2D to predefined frame CCSprite. But the image gets cropped to the desired frame which is not wanted. Can someone tell me how to get the original image from server to desired frame without getting cropped. Thanks.
try :
CCSprite *temp = [CCSprite spriteWithTexture:[[CCTexture2D alloc] initWithImage:[UIImage imageWithData:data] resolutionType:kCCResolutioniPhoneFourInchDisplay]];
float scaleX = 70./temp.contentSize.width;
float scaleY = 70./temp.contentSize.height;
// if you want to preserve the original texture's aspect ratio
float scale = MIN(scaleX,scaleY);
temp.scale = scale;
// or if you want to 'stretch-n-squeeze' to 70x70
temp.scaleX = scaleX;
temp.scaleY = scaleY;
// then add the sprite *temp
usual disclaimer : not tested, done from memory, beware of divides by 0 :)

Parallax Scrolling for the Endless Game background using cocos2D

I am newbie programmer in cocos2D.... I wanted to create the Endless Background using the Parallax Scrolling.. I am trying to learn the Parallax but it doesn't update with the time and sprites doesn't keep on rotating from top to bottom! The snippet i tried is as below
-(id) init
{
if((self = [super init]))
{
CGSize wSize = [CCDirector sharedDirector].winSize;
self.isTouchEnabled = YES;
CGPoint topOffset = CGPointMake(wSize.width, 0);
CGPoint midOffset = CGPointMake(wSize.width/2,0);
CGPoint downOffset = CGPointZero;
CCSprite *para1 = [CCSprite spriteWithFile:#"Default.png"];
CCSprite *para2 = [CCSprite spriteWithFile:#"Icon.png"];
CCSprite *para3 = [CCSprite spriteWithFile:#"Default.png"];
CCSprite *para4 = [CCSprite spriteWithFile:#"Icon.png"];
paraNode = [CCParallaxNode node];
[paraNode addChild:para1 z:1 parallaxRatio:CGPointMake(0.5f, 0)
positionOffset:topOffset];
[paraNode addChild:para2 z:2 parallaxRatio:CGPointMake(1, 0) positionOffset:topOffset];
[paraNode addChild:para3 z:4 parallaxRatio:CGPointMake(2, 0) positionOffset:midOffset];
[paraNode addChild:para4 z:3 parallaxRatio:CGPointMake(3, 0) positionOffset:downOffset];
[self addChild:paraNode z:0 ];
[self scheduleUpdate];
}
return self;
}
-(void) update : (ccTime) dt
{
//Need to move the Parallax Node with the repetition of the background
}
This is the Implementation file... I am stuck here for moving the contiunous moving of the background in the Horizontal or Portrait mode.
Thanks for the Help in Advance
CCParallaxNode doesn't support endless scrolling, unless you modify its code. I have an example for endless parallax scrolling in my Learn Cocos2D book. From that link you can also download the book's source code where you'll find the parallax class in chapters 6 to 8.
I have created a simple class named ParallaxManager which is capable for creating infinite parallax effect for both small sprite like small cloud
as well large layer sprite like grass.
You can find out the complete project from GitHub.

IOS: move an UIImageView

In my app I want to move a little UIImageView with inside a .png; this is a little insect and I want to simulate his flight. At example I want that this png do when it move an inverted eight as the infinite simbol ∞
You may use CoreAnimation. You can subclass a view, create a subview for the insect, and then assign an animation to it, following a defined path.
Your UIImageView could be animated. If it's a fly, you can do a few frames for wing moves:
NSArray *images = [NSArray arrayWithObjects:..., nil];
insect.animationImages = images;
insect.animationDuration = ??;
insect.animationRepeatCount = 0;
[insect startAnimating];
Then set an init frame for the insect:
insect.frame = CGRectMake(-120, 310, [[images objectAtIndex:0] size].width, [[images objectAtIndex:0] size].height);
And then define the path:
CGMutablePathRef aPath;
CGFloat arcTop = insect.center.y - 50;
aPath = CGPathCreateMutable();
CGPathMoveToPoint(aPath, NULL, insect.center.x, insect.center.y);
CGPathAddCurveToPoint(aPath, NULL, insect.center.x, arcTop, 240, -100, 490, 360);
CAKeyframeAnimation* arcAnimation = [CAKeyframeAnimation animationWithKeyPath: #"position"];
arcAnimation.repeatCount = HUGE_VALF;
[arcAnimation setDuration: 4.5];
[arcAnimation setAutoreverses: NO];
arcAnimation.removedOnCompletion = NO;
arcAnimation.fillMode = kCAFillModeBoth;
[arcAnimation setPath: aPath];
CFRelease(aPath);
[insect.layer addAnimation: arcAnimation forKey: #"position"];
I leave how to do the infinite loop path up to you :)
Hope it helps!
Normally, if you were to be moving things around, I'd suggest using [UIView animate...]. However, you want something to move on a complex, curvy path. So instead, I'd suggest coming up with an equation that gives the (x,y) for the insect as a function of time, and then start an NSTimer with a fairly small time interval, and every time you get an update, move the insect (perhaps using [UIView animate...]).
Another way to go is to use a 2-d animation framework such as cocos2d - then, you can get an 'update' call linked to the frame refresh rate, inside of which you update the position of your insect using the same equation as from above.

Rotate or flip the square image in cocos2d

Assume that one square image is for showing road. Now In my game I have to flip this square image on Y axis so that it looks like road and person can walk on that road. I want this type of rotation.
But I want the same rotation in cocos2d then how I have to do it?
Thanks for help
I don't completely understand what you want to do, but I'll do my best here :)
You could use the flipX or flipY properties of a CCSprite
E.X.
CCSprite *sprite = [CCSprite spriteWithFile:#"file.png"];
sprite.position = position;
sprite.flipX = YES;
[self addChild:sprite];
or you could use a rotate action as Anish said.
Hope that helped.
Rotating Turrets in Cocos2D
Try like this...
CCRotateBy *rot = [CCRotateBy actionWithDuration: 2 angle: 720];
[sprite runAction:rot];
CCSprite *sprite = [CCSprite spriteWithFile:#"file.png"];
sprite.rotation = 45;
I Flip CCSprite at Y axis like that in android...
CCSprite sprite=CCSprite.sprite("icon.png");
CCIntervalAction a = (CCIntervalAction)CCOrbitCamera.action(2, 1, 0, 0, 360, 0, 0);
addChild(sprite,1);
sprite.runAction(CCRepeatForever.action(a));