How to get perfect collision between 2 sprite in cocos 2D - cocos2d-iphone

I have 2 sprite. for collide i use bounding box. But its not perfect collision. its collide with transparent image also. i need perfect collision.
Suppose i have :
CCSprite *sprite1 = [CCSprite spriteWithFile:#"image.png"];
CCSprite *sprite2 = [CCSprite spriteWithFile:#"image.png"];
if (CGRectIntersectsRect([sprite1 boundingBox], [sprite2 boundingBox]))
{
// Collision Detected ....
}
But its create a prob . its collide but not perfectly collide.
anybody can help me? Thanks in advance

CCSprite *player = [CCSprite spriteWithFile:#"image.png"];
[self addChild:player];
CCSprite *enemy = [CCSprite spriteWithFile:#"image.png"];
[self addChild:enemy];
float pos_x = player.position.x - enemy.position.x;
float pos_y = player.position.y - enemy.position.y;
float pos_xy = (pos_x * pos_x) + (pos_y * pos_y);
float Collision = (10+5) * (10+5); // Let 10 be the radious of player & 5 be the radious of enemy
if (pos_xy <= Collision)
{
// Collision Detected
}
// But its is only for round shaped image . like: Ball.
And its create perfect collision using pythagorean Theorm

Related

Move a whole animation sprite sheet

I have some sprite-sheet that i have to animate forever , and i would like to add it as a CCLayer
to my scene .
Later on , i have to move this whole animation sprite on the screen.
So, for example, i have some animation of a dog walking, from sprite sheet, this one is running forever. than i want to be able to move this dog on screen while animating.
What is the best way to do this ? (or the right way)
This is how i animate the frames :
CCSprite *boom;
boom = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:#"%#_00000.png",file]];
boom.position=touch;
[self addChild:boom];
NSMutableArray *animFrames = [NSMutableArray array];
for(int i = 0; i < 5; i++)
{
CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:
#"%#_0000%i.png",file,i]];
[animFrames addObject:frame];
}
CCAnimation* boxAnimation = [CCAnimation animationWithSpriteFrames:animFrames delay:0.075f];
CCAnimate * boxAction = [CCAnimate actionWithAnimation:boxAnimation];
CCAction *call=[CCCallBlock actionWithBlock:^{[self removeFromParentAndCleanup:YES];}];
CCAction * sequence=[CCSequence actions:boxAction,[CCHide action],call,nil];
[boom runAction:sequence];
return self;
How would you move this whole thing ?
There are a few ways to do this. If you are not preocupied with collision detection, then one way would be to :
CGPoint egressPosition = ccp(0,0); // figure this out in your app
float moveDuration = 1.5f ; // whatever time you compute for desired speed and distance
id move = [CCMoveTo actionWithDuration:moveDuration position:egressPosition];
id spawn = [CCSpawn actions:sequence,move,nil];
[boom runAction:spawn];
otherwise, using your code as is
[self schedule:#selector(moveBox:)]; // optional, you could do this in update method
[boom runAction:sequence];
-(void) moveBoom:(CCTime) dt {
CGPoint newPosition;
delta = ccp(dt*speedX,dt*speedY); // crude , just to get the idea
newPosition = ccpAdd(boom.position,delta);
// here you can figure out collisions at newPosition before the collision
// and do whatever seems appropriate
boom.position = newPosition;
}

Camera following the touched body

I need to have the Cocos2d camera follow a sprite (attached to a Box2D body) that the user is touching on the screen. As the user is dragging the player around, I need it to be able to go to other parts of the world. This has to be through touch, and not automatic scrolling.
I tried several approaches based on tutorials but nothing seem to address this issue. For example the solution offered here Move CCCamera with the ccTouchesMoved method? (cocos2d,iphone) by #Michael Fredrickson has the entire layer move, but when it moves, the sprites / bodies on the screen have unmatched coordinations and when I test to see if they're touched, the if(fixture->TestPoint(locationWorld)) fails.
I also looked at the tutorials here http://www.learn-cocos2d.com/2012/12/ways-scrolling-cocos2d-explained/ but this also isn't what I'm looking for.
Any help would be greatly appreciated.
EDIT:
I'm accepting Liolik's answer below because it put me on the right track. The last piece of the puzzle, though, is to make the value received from the getPoint method an instance variable, and deduce it from locationWorld which I'm doing the TestPoint against. Like this:
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
b2Vec2 diff = b2Vec2(difference.x, difference.y);
for (b2Body* b = _world->GetBodyList(); b; b = b->GetNext()) {
b2Fixture* f = b->GetFixtureList();
while(f != NULL) {
if(f->TestPoint(locationWorld-diff)) {
b2MouseJointDef def;
def.bodyA = _groundBody;
def.bodyB = b;
def.target = locationWorld-diff;
def.maxForce = 9999999.0f * b->GetMass();
_mouseJoint = (b2MouseJoint*)_world->CreateJoint(&def);
b->SetAwake(true);
}
f = f->GetNext();
}
}
in update function :
CGPoint direction = [self getPoint:myBody->GetPosition()];
[self setPosition:direction];
- (CGPoint)getPoint:(b2Vec2)vec
{
CGSize screen = [[CCDirector sharedDirector] winSize];
float x = vec.x * PTM_RATIO;
float y = vec.y * PTM_RATIO;
x = MAX(x, screen.width/2);
y = MAX(y, screen.height/2);
float _x = area.width - (screen.width/2);
float _y = area.height - (screen.height/2);
x = MIN(x, _x);
y = MIN(y, _y);
CGPoint goodPoint = ccp(x,y);
CGPoint centerOfScreen = ccp(screen.width/2, screen.height/2);
CGPoint difference = ccpSub(centerOfScreen, goodPoint);
return difference;
}
So if i understand correctly, when the sprite is inside of the middle of the screen, the background is stationary and the sprite follows your finger, but when you scroll toward the edge, the camera starts to pan?
I had something roughly similar in my game Star Digger where there's a ship in the middle of the screen on its own layer that has to fly around the world, and had the same problem when the ship fired bullets into the main world layer.
heres what I did:
float thresholdMinX = winSize*1/3;
float thresholdMaxX = winSize*2/3;
if(touch.x > thresholdMaxX) //scrolling right
{
self.x += touch.x - thresholdMaxX;
}
else if(touchX < thresholdMinX)
{
self.x += thresholdMinX - touchX;
}
else
{
sprite.position = touch;
}
CGPoint spritePointInWorld = ccp(sprite.x - self.x, sprite.y - self.y);
then every time you calculate collisions, you need to recompute the sprites "actual" position in the world, which is its screen position minus the worlds offset, instead of the sprites screen position.

side scrollling boundaries in cocos2d with levelhelper

I am making a side scrolling game with levelhelper and sneakyinput.
i have couple questions.
i have sneakyinput on a different layer and i am facing a problem on scrolling with the parallax at levelhelper.
i cant manage to apply boundaries and move the layer properly.
how i will fix the scrolling? to be inside the boundaries and the character centered?
i have those 2 methods inside the update method
-(void) update:(ccTime)deltaTime{
[self applyJoystick:_leftJoystick forTimeDelta:deltaTime];
[self setViewpointCenter:hero.position];}
-(void)applyJoystick:(SneakyJoystick *)aJoystick forTimeDelta:(float)delta{
CGRect worldRect = [loader gameWorldSize];
CGPoint scaledVelocity=ccpMult(aJoystick.velocity, 90.0f);
CGPoint newPosition =ccp(hero.position.x+scaledVelocity.x*delta, hero.position.y +scaledVelocity.y *delta);
float posX = MIN(worldRect.origin.x + worldRect.size.width - hero.centerToSides, MAX(hero.centerToSides, newPosition.x));
float posY = MIN(worldRect.origin.y + worldRect.size.height - hero.centerToBottom, MAX(hero.centerToBottom, newPosition.y));
[hero setPosition:cpp(posX,posY)];}
-(void)setViewpointCenter:(CGPoint) position {
CGSize winSize = [[CCDirector sharedDirector] winSize];
CGRect worldRect = [loader gameWorldSize];
CGPoint centerOfView = ccp(winSize.width/2, winSize.height/2);
int x = MAX(position.x, worldRect.origin.x + winSize.width / 2);
int y = MAX(position.y, worldRect.origin.y + winSize.height / 2);
x = MIN(x, (worldRect.origin.x + worldRect.size.width) - winSize.width / 2);
y = MIN(y, (worldRect.origin.y + worldRect.size.height) - winSize.height/2);
CGPoint actualPosition = ccp(x, y);
CGPoint viewPoint = ccpSub(centerOfView, actualPosition);
self.position = viewPoint;}
also i try to flip the character (LHSprite) i use
if (newPosition.x< hero.position.x)
hero.flipX=YES;
else
hero.flipX = YES;
but isnt working but i tried to use also
hero.scaleX=-1
to flip it instead of flipX,flips but goes to the other side of the screen fliped.
solved partially.
it seemed that
myParallax = [loader parallaxNodeWithUniqueName:#"Parallax_1"];
was messing it up so i disable it,
i change the first method to
-(void)applyJoystick:(SneakyJoystick *)aJoystick forTimeDelta:(float)delta{
CGRect worldRect = [loader gameWorldSize];
CGSize winSize = [[CCDirector sharedDirector] winSize];
CGPoint scaledVelocity=ccpMult(aJoystick.velocity, 200.0f);
CGPoint newPosition =ccp(hero.position.x+scaledVelocity.x*delta, hero.position.y +scaledVelocity.y *delta);
float posX = MIN(worldRect.size.width - hero.centerToSides, MAX(hero.centerToSides, newPosition.x));
float posY = MIN(winSize.height -winSize.height/2+ hero.centerToBottom, MAX(hero.centerToBottom, newPosition.y));
if (scaledVelocity.x >= 0)
hero.scaleX = 1.0;
else
hero.scaleX = -1.0;
[hero setPosition:ccp(posX, posY)];
}
it seems when the scrolling isnt correct and goes to white area out of the world and everything is correct you need to find an equation about parallax ratio and levelsize and velocity.

Cocos2d. Rotate point around another point without hard math calculations?

I haven't seen easy examples about rotaion around a specified point. I tried something like this but it doesn't work:
//CCNode *node is declared
//In a function of a subclass of CCSprite
- (void)moveWithCicrlce
{
anchorNode = [CCNode node];
anchorNode.position = ccpSub(self.position, circleCenter);
anchorNode.anchorPoint = circleCenter;
[anchorNode runAction:[CCRotateBy actionWithDuration:1 angle:90]];
[self runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCCallFunc actionWithTarget:self selector:#selector(rotate)], [CCDelayTime actionWithDuration:0.1], nil]]];
}
- (void)rotate
{
self.position = ccpAdd(anchorNode.position, anchorNode.anchorPoint);
}
Here's how you can rotate a node (sprite etc) around a certain point P (50,50) with a radius (distance from P) of 100:
CCNode* center = [CCNode node];
center.position = CGPointMake(50, 50);
[self addChild:center];
// node to be rotated is added to center node
CCSprite* rotateMe = [CCSprite spriteWithFile:#"image.png"];
[center addChild:rotateMe];
// offset rotateMe from center by 100 points to the right
rotateMe.position = CGPointMake(100, 0);
// perform rotation of rotateMe around center by rotating center
id rotate = [CCRotateBy actionWithDuration:10 rotation:360];
[center runAction:rotate];
My approximate solution:
#interface Bomb : NSObject {
CCSprite *center;
}
...
#end
and some methods:
- (void)explode
{
BombBullet *bullet = [BombBullet spriteWithFile:#"explosion03.png"];
[[[CCDirector sharedDirector] runningScene] addChild:bullet];
center = [CCSprite spriteWithTexture:bullet.texture];
center.position = explosionPoint;
center.anchorPoint = ccp(-0.5, -0.5);
center.visible = NO;
[[[CCDirector sharedDirector] runningScene] addChild:center];
[center runAction:[CCRotateBy actionWithDuration:1 angle:360]];
CCCallFunc *updateAction = [CCCallFuncN actionWithTarget:self selector:#selector(update:)];
[bullet runAction:[CCRepeatForever actionWithAction:[CCSequence actions:updateAction, [CCDelayTime actionWithDuration:0.01], nil]]];
}
- (void)update:(id)sender
{
BombBullet *bombBullet = (BombBullet *)sender;
bombBullet.rotation = center.rotation;
bombBullet.position = ccpAdd(center.position, center.anchorPointInPoints);
bombBullet.position = ccpAdd(bombBullet.position, ccp(-bombBullet.contentSize.width / 2, -bombBullet.contentSize.height / 2));
bombBullet.position = ccpRotateByAngle(bombBullet.position, center.position, bombBullet.rotation);
}
of course I should add sprite deleting.

Cocos2d scrolling scale sprite

I apologize for my English. Sprite size of 1 x 12 px, after I had to scaleX and try to scroll, I have nothing. Any of your ideas. Thank you!
Here's the code:
-(void) proba
{
CGPoint pos = ccp(50,100);
int dlin = 200;
wall = [CCSprite spriteWithFile:#"wall.png"]; //wall.png 1x12px
wall.scaleX = dlin;
wall.anchorPoint = ccp(0, 0.5);
wall.position = pos;
[self addChild:wall];
[self schedule:#selector(wall_scroll)];
}
-(void) wall_scroll
{
static float offset = 0.1f;
wall.textureRect = CGRectMake(wall.textureRect.origin.x - offset ,
wall.textureRect.origin.y ,
wall.scaleX,
wall.textureRect.size.height);
}
Instead of trying to scroll the textureRect, could you scroll the whole wall layer using wall.position?