cocso2d pinch-zoom like Fieldrunners - objective-c

I've been trying to set up the parallax node correctly but need some help with this.
This http://goo.gl/Piqy5 would be the frame of the game and for the parallax node area I have 3 layers:
background layer (zoomable but not scrollable, z order -1)
layer 1 (z order 1)
layer 2 (z order 2)
//Adding the layers to the parallax node
CGPoint offsetLayer = ccp(0,0);
//background layer
[parallaxNode addChild:backgroundLayer z:-1 parallaxRatio: ccp(0,0) positionOffset: offsetLayer];
//layer 1
[parallaxNode addChild:secondParallaxLayer z:1 parallaxRatio: ccp(0.5,0) positionOffset: offsetLayer];
//layer 2
[parallaxNode addChild:firstParallaxLayer z:2 parallaxRatio: ccp(1.1,0) positionOffset: offsetLayer];
//the pan/zoom & scroll controller
_controller = [[CCPanZoomController controllerWithNode:baseLayer] retain];
_controller.boundingRect = boundingRect;
_controller.zoomOutLimit = _controller.optimalZoomOutLimit;
_controller.zoomInLimit = 2.0f;
[_controller centerOnPoint:CGPointMake(screenSize.width/2.0, screenSize.height/2.0)];
[_controller enableWithTouchPriority:-2 swallowsTouches:YES];
I think I should fix using:
//Setting the touch delegate to my CCScene
#interface GameScene : CCScene <CCStandardTouchDelegate>
//and add register to touch delegate
[[CCTouchDispatcher sharedDispatcher] addStandardDelegate:self priority:2];
- (CGPoint)convertPoint:(CGPoint)point fromNode:(CCNode *)node {
return [self convertToNodeSpace:[node convertToWorldSpace:point]];
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
#define CLAMP(x,y,z) MIN(MAX(x,y),z)
if ([[[event allTouches] allObjects] count] == 2) {
UITouch* touch1 = [[[event allTouches] allObjects] objectAtIndex:0];
UITouch* touch2 = [[[event allTouches] allObjects] objectAtIndex:1];
// calculate scale value
double prevDistance = ccpDistance([touch1 previousLocationInView:[touch1 view]], [touch2 previousLocationInView:[touch2 view]]);
double newDistance = ccpDistance([touch1 locationInView:[touch1 view]], [touch2 locationInView:[touch2 view]]);
CGFloat relation = newDistance / prevDistance;
CGFloat newScale = self.scale * relation;
if ((newScale >= MIN_SCALE) && (newScale <= MAX_SCALE)) {
CGPoint touch1Location = [baseLayer convertTouchToNodeSpace:touch1];
CGPoint touch2Location = [baseLayer convertTouchToNodeSpace:touch2];
// calculate center point between two touches
CGPoint centerPoint = ccpMidpoint(touch1Location, touch2Location);
// store center point location (ScrollableView space)
CGPoint centerPointInParentNodeSpace = [self convertPoint:centerPoint fromNode:baseLayer];
CGPoint oldPoint = ccp(centerPointInParentNodeSpace.x * (self.scale), centerPointInParentNodeSpace.y * (self.scale));
self.scale = newScale;
CGPoint newPoint = ccp(centerPointInParentNodeSpace.x * (self.scale), centerPointInParentNodeSpace.y * (self.scale));
CGPoint diff = ccp(oldPoint.x - newPoint.x , oldPoint.y - newPoint.y);
[baseLayer setPosition:ccp(baseLayer.position.x + (diff.x*(1/self.scale)), baseLayer.position.y + (diff.y*(1/self.scale)))];
}
} else if ([[[event allTouches] allObjects] count] == 1) {
// get touch locations
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPosition = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
CGPoint oldPosition = [[CCDirector sharedDirector] convertToGL:[touch previousLocationInView:[touch view]]];
// calculate difference in position
CGPoint diff = ccpSub(touchPosition, oldPosition);
self.position = ccpAdd(self.position, diff);
}
#undef CLAMP
}
Any remarks or help would be great! :)

Check out CCLayerPanZoom in the Cocos2d Extensions on Github. I have used this class to enable pinch zoom and pan in my game

Related

SKSpriteNode Targeting

So RIGHT NOW my code presents 7 playing cards. If the playing card is pressed it moves removes the card from the playerCard array and adds it to the playedCards array. The problem is, is move the card I target it with a SKNode in the touchesBegan method;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node isKindOfClass:[CardSpriteNode class]]) {
Okay, no problem, the card moves up. The problem is, All the other cards left in the playerCards now need to move i.e ( tighten up ) as they were originally. Here's my formula for distances between them;
int cardsLaid = i * (cardDisplay.size.width / 3);
So I can now get the cards that are originally displayed and the ones that are touched, to form a nice gap between them.
What I need to do is to move the cards back to a nice gap, after one of the cards between them has been moved
for (int i = 0; i < [playerCards count]; i++) {
int cardsLaid = i * (cardDisplay.size.width / 3);
CGPoint forPoint = CGPointMake((0.5 - (self.frame.size.width / 4)) + cardsLaid, 0.0);
playerCards[i] //Here I need to target each skspritenode.name for each playerCards
[??? runAction:[SKAction moveTo:forPoint duration:0.6]];
}
So I need to target each SKSpritenode.name by the names saved in the playerCards MutableArray. Then once I've targetted a spritenode I need to move it where the ??? is.
Here's my entire touchesBegan method if it helps.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node isKindOfClass:[CardSpriteNode class]]) {
int add = (int)[playerCards count] * (cardDisplay.size.width / 3);
CGPoint origPos = CGPointMake(-self.frame.size.width/2.8 + add, -218);
if ([cardsPlayed containsObject:node.name]) {
//Card is already played, return to original position and remove from array.
CGPoint point = origPos;
[node runAction:[SKAction moveTo:point duration:0.6]];
node.zPosition = zPosCount;
zPosCount += 1;
[cardsPlayed removeObject:node.name];
[playerCards addObject:node.name];
NSLog(#"this ran");
} else {
//Card is not already played, position to add card and add to array.
amountOfCardsLaid = (int)[cardsPlayed count] * (cardDisplay.size.width / 3);
CGPoint point = CGPointMake((0.5 - (self.frame.size.width / 4
)) + amountOfCardsLaid, 0.0);
[node runAction:[SKAction moveTo:point duration:0.6]];
node.zPosition = zPosCount;
zPosCount += 1;
[playerCards removeObject:node.name];
[cardsPlayed addObject:node.name];
for (int i = 0; i < [playerCards count]; i++) {
int cardsLaid = i * (cardDisplay.size.width / 3);
CGPoint forPoint = CGPointMake((0.5 - (self.frame.size.width / 4)) + cardsLaid, 0.0);
playerCards[i]
[??? runAction:[SKAction moveTo:forPoint duration:0.6]];
}
}
//Hide.Unhide buttons
if ([cardsPlayed count] == 0) {
if (addButton.hidden == FALSE) addButton.hidden = true;
if (cancelButton.hidden == FALSE) cancelButton.hidden = true;
} else {
if (addButton.hidden == TRUE) addButton.hidden = false;
if (cancelButton.hidden == TRUE) cancelButton.hidden = false;
}
}
}
The gap I need to close is on the bottom playerCards
SKNode *tempNode = [self childNodeWithName:playerCards[i]];
After a few days. fml

SKSpriteNode rotation not working properly

I'm trying to rotate a SKSpriteNode by using UIRrotationGestureRecognizer. I've implemented a code but sometimes, when I rotate the node it jumps to a rotation that isn't the one it should be. Here you have the code:
- (void) handleRotation:(UIRotationGestureRecognizer *) rotationrecognizer{
CGFloat initialrotation = 0.0;
if (rotationrecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint touchLocation = [rotationrecognizer locationInView:rotationrecognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
[self selectNodeForTouch:touchLocation];
initialrotation = selected.zRotation;
}
else if (rotationrecognizer.state == UIGestureRecognizerStateChanged) {
CGFloat angle = initialrotation + rotationrecognizer.rotation;
selected.zRotation = angle;
}
}
You are resetting initial rotation to 0 on every call... you should move this to be an ivar of your view if you need it to stay resident.
The way you have it written now, the line that sets 'angle' is effectively equal to this:
CGFloat angle = 0 + rotationrecognizer.rotation;
Instead, you should do the following (where initialRotation is defined as a private ivar):
- (void) handleRotation:(UIRotationGestureRecognizer *) rotationrecognizer{
if (rotationrecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint touchLocation = [rotationrecognizer locationInView:rotationrecognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
[self selectNodeForTouch:touchLocation];
_initialrotation = selected.zRotation;
}
else if (rotationrecognizer.state == UIGestureRecognizerStateChanged) {
CGFloat angle = _initialrotation + rotationrecognizer.rotation;
selected.zRotation = angle;
}
}

Adding and touching multiple sprites in cocos2d

I have a class where I add multiple sprites as shown in the code below:
CCSprite *b = [CCSprite spriteWithFile:#"b"];
b.position = ccp(100, 160);
CCSprite *b2 = [CCSprite spriteWithFile:#"b2.png"];
b2.position = ccp(115, 150);
CCSprite *b3 = [CCSprite spriteWithFile:#"b3.png"];
b.position = ccp(200, 150);
CCSprite *b4 = [CCSprite spriteWithFile:#"b4.png"];
b4.position = ccp(220, 145);
b.anchorPoint = ccp(0.98, 0.05);
b2.anchorPoint = ccp(0.03, 0.05);
b3.anchorPoint = ccp(0.03, 0.05);
b4.anchorPoint = ccp(0.95, 0.05);
[self addChild:b z:1 tag:1];
[self addChild:b2 z:1 tag:2];
[self addChild:b3 z:1 tag:3];
[self addChild:b4 z:1 tag:4];
Here's the code for the touch event:
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
//Swipe Detection - Beginning point
beginTouch = location;
for(int i = 0; i < [hairArray count]; i++)
{
CCSprite *sprite = (CCSprite *)[hairArray objectAtIndex:i];
if(CGRectContainsPoint([sprite boundingBox], location))
{
//selectedSprite is a sprite declared on the header file
selectedSprite = sprite;
}
}}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//Move touched sprite
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
if(selectedSprite != nil)
{
selectedSprite.position = ccp(location.x, location.y);
}}
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//End point of sprite after dragged
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
endTouch = location;
posX = endTouch.x;
//Minimum swipe length
posY = ccpDistance(beginTouch, endTouch);
[self moveSprite];}
Now, the actions itself work just fine but the trouble I'm having is that if I want to drag b2, I have to drag b3 and b4 first. I'm not sure if it has anything to do with the z-index or it is because of the transparent areas that is present for each sprite. Is there something I'm missing here?
if(CGRectContainsPoint([sprite boundingBox], location))
{
//selectedSprite is a sprite declared on the header file
selectedSprite = sprite;
}
This code updates the currently selected sprite as soon as a new one is found while looping on all sprites. This means that if 3 sprites overlap you will get that the selected one is the last one in the array of nodes of the parent.
You can't make any assumptions on the orders so this is not clearly what you want, you have to decide a policy to give sprites priority. Mind that editing the anchorPoint may alter the position of the sprite compared to the bounding box (so that the bounding box is even outside the sprite).
To be sure of it you should enable:
#define CC_SPRITE_DEBUG_DRAW 1
in ccConfig.h. This will render bounding boxes around sprites.

Getting location of sprite within array cocos2d`

I need to be able to touch a specific moving sprite in my array and perform an action on it. However when I perform my MoveTo action, the sprite location doesn't update. Help!
Array:
int numbreds = 7;
redBirds = [[CCArray alloc] initWithCapacity: numbreds];
for( int i = 1; i<=numbreds; i++){
int xvalue = ((-50*i) + 320);
int yvalue= 160;
if (i==4)
{
CCSprite *parrot = [CCSprite spriteWithFile:#"taco.png"];
[birdLayer addChild:parrot];
[self movement]; //the action that moves the array horizontally
parrot.position = ccp(xvalue,yvalue);
parrot.tag=100;
Touch
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
CCSprite *mark = (CCSprite *)[birdLayer getChildByTag:100];
if (CGRectContainsPoint([mark boundingBox], location))
{
CCLOG(#"YAY!");
}
THe problem is that the location of the CCSprite doesn't actually update or move. YAY! only is generated at the origin location of the sprite.
Try this:
CCSprite *temp = [CCSprite spriteWithFile:#"taco.png"];
temp = [birdLayer getChildByTag:100];
if (temp.position.x == location.x) {
// do stuff...
}

Cocos2d rotation on touches moved problem

I have a spear like sprite. It rotation is decided by touchesMoved method. whenever the user slides his finger it points towards that touch. This is my method:
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
float angleRadians = atanf((float)location.y / (float)location.x);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
spear.rotation = -1 * angleDegrees;
}
This kinda works, but only from 0 to 45 degrees. and it goes opposite. So as I am moving from finger for bottom to top, it rotates clockwise (it should follow direction of fnger and rotate counter clockwise). From 45 to 90, it works fine (moves counter clickwise) but only if i start the touch in upper diagonal of the screen.
What am i doing wrong?
Thanks
#define PTM_RATIO 32
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
for( UITouch *touch in touches ) {
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
spriteBody->SetTransform(locationWorld,spriteBody->GetAngle());
}
}
-(void) tick: (ccTime) dt
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int32 velocityIterations = 8;
int32 positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
m_world->Step(dt, velocityIterations, positionIterations);
// for (int i = 0; i < (int)birds.size(); i++)
// birds[i]->render();
//Iterate over the bodies in the physics world
for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite *myActor = (CCSprite*)b->GetUserData();
myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
Figured out what was wrong. I needed to change the CGPoint I got from the touches into GL point like this:
CGPoint location = [touch locationInView: [touch view]];
location = [[CCDirector sharedDirector] convertToGL: location];
Silly me. Should have thought about this before.
CGPoint touchLocation = [touch locationInView: [touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
touchLocation = [self convertToNodeSpace:touchLocation];
GPoint diff = ccpSub(touchLocation, _player.position);
//rotate to face the touch
CGPoint diff = ccpSub(_player.position, touchLocation);
float angleRadians = atanf((float)diff.y / (float)diff.x);
float angleDegrees = CC_RADIANS_TO_DEGREES(angleRadians);
float cocosAngle = -1 * angleDegrees;
if(diff.x < 0)
{
cocosAngle += 180;
}
id actionRotateTo = [CCRotateTo actionWithDuration:0.1 angle:cocosAngle];
[_player runAction:actionRotateTo];