How do I animate a sprite using cocos2d? - iphone

I have a sprite which will move right,left and jump.
I need to add the action to a animated sprite ie an animated sprite should jump, turn right and left.
Can anyone please tell me how to do it with sample code.

This is quite simple with cocos2d code here:
Sprite *mySprite = [Sprite spriteWithFile#"mySprite.png"];
[mySprite setPosition:ccp(x,y)];
[self addChild:mySprite]; //This displays the Sprite in your layer
Now for the sequence you intend to do...
id moveRight = [MoveBy actionWithDuration:2 position ccp(x+k,y) //Where k is how much to the right you want it to go.
id moveLeft = [MoveBy actionWithDuration:2 position ccp(x-k,y)];
id jump = [JumpBy actionWithDuration:1 position:ccp (x,y) height:1 jumps:1];
id sequence = [Sequence actions:moveRight,moveLeft,jump,nil];
[mySprite runAction:sequence];
Hope that's clear.
-Oscar

Related

Sprite Kit shooting projectiles at target

I wanted to make my turret Sprite shoot at the monster. i have already got the turret to turn to the monster and follow it until its out of range, now i just need to make the shooting occur.
what is the best way to shoot a projectile from the turret to the monster?
i have already done this part:
-(void)shoot
{
SKSpriteNode *bullet = [SKSpriteNode spriteNodeWithImageNamed:#"CannonMissile-hd.png"]; ... i don't know what to do next
}
also, i need it to shoot at intervals of x seconds,
thanks
-(void)shoot
{
SKSpriteNode *turretNode;//I assume you have this node already in the scene . Dont use this line
SKSpriteNode *enemy;//I assume you have this node already in the scene . Dont use this line
SKSpriteNode *bullet = [SKSpriteNode spriteNodeWithImageNamed:#"CannonMissile-hd.png"];
bullet.zPosition = turretNode.zPosition -1;//if you want your bullet not to spawn on top of your turret
[turretNode addChild:bullet];
//you need to set the physics body of the bullet so you can detect contacts
SKAction *move = [SKAction moveTo:enemy.position duration:0.5];//if u have multiple enemies then you have to deceide which one to hit
[bullet runAction:move completion:^{
[bullet removeFromParent];//removes the bullet when it reaches target
//you can add more code here or in the didBeginContact method
}];
//repeat the process
[self performSelector:#selector(shoot) withObject:nil afterDelay:5];//replace 5 with ur x seconds
//that's it
}

Is there a way to make a soft body with Spritekit using SKSpriteNode and PhysicsBody parameters?

I have the following sprite that falls to the bottom of the screen:
// The View
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
self.physicsWorld.contactDelegate = self;
// The Sprite
SKSpriteNode *cube = [[SKSpriteNode alloc] initWithImageNamed:#"cube"];
[cube setPosition:CGPointMake(160,250);
[self addChild:cube];
// The Physics
cube.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:cube.frame.size];
cube.physicsBody.dynamic = YES;
cube.physicsBody.affectedByGravity = YES;
cube.physicsBody.mass = 0.02;
Is there a way to make it so its sides are bulging when it hits the bottom border of the screen? Something that would be Jelly like or a soft body that still maintains its shape to some extent but bulges out under its own weight? I hope this makes sense....
Visit the site https://gist.github.com/kazukitanaka0611/4b9d4ac9dff0cd317b6c it have explanation and source code for soft bodies (jelly) in sprite kit
quick and easy way without math:
1 use flash to tween your box warping.
2 export the tweened frames as a sprite sheet (texture atlas)
3 animate the texture atlas on contact with an edge physics body in your scene.
your box will fall and on contact animate the separate images to give the impression its warping/bulging sides.
i used this method and it works - in other words it gives the desired effect, which in my view is what is important - your gamers don't care how you did it, as long as it looks great.

How to move the PhysicsSprite in box2d

I am having a physicsSprite of kinematics body type and I want to move the body and sprite bit down and back to its position. I tried it like this Inside update method:
for (NSValue *bodyValue in [self getGoalPostBodiesList])
{
b2Body *gPBody = (b2Body *)[bodyValue pointerValue];
PhysicsSprite *pSprite =(PhysicsSprite *) gPBody->GetUserData();
NSLog(#"\n tag value of Sprite = %d",pSprite.tag);
if(pSprite == goal1)
{
pSprite.position = CGPointMake((gPBody->GetPosition().x)*32.0,(gPBody->GetPosition().y)*32.0);
float angle = gPBody->GetAngle();
pSprite.rotation = -(CC_RADIANS_TO_DEGREES(angle));
id moveDownAction = [CCMoveTo actionWithDuration:0.5 position:CGPointMake(pSprite.position.x,(pSprite.position.y )- 40)];
id moveUpAction = [CCMoveTo actionWithDuration:0.5 position:CGPointMake(pSprite.position.x,(pSprite.position.y )+ 40)];
CCSequence *seqAction = [CCSequence actions:moveDownAction,moveUpAction, nil];
[pSprite runAction:seqAction];
b2Vec2 pos = b2Vec2(pSprite.position.x/32.0, pSprite.position.y/32.0);
gPBody->SetTransform(pos, CC_DEGREES_TO_RADIANS(pSprite.rotation));
gPBody->SetLinearVelocity(b2Vec2(0.0f, 0.0f));
gPBody->SetAngularVelocity(0.0f);
}
}
Still the sprite is not changing its position.
Anyone's help will be deeply appreciated.
Thanks all,
MONISH
To summarize your code, you update the position of your sprite to reflect that of the body, start an animation, and then update the position of the body to correspond to the position of the sprite. So naturally, nothing should move here, since your CCMoveTo actions have not exerted any effect on your sprite yet.
Second, your update method may be called very often, like dozens of times per second, so the animation gets reset continously and will not make any visible progress.
To follow a consistent pattern, how about you set the velocity of your kinematic bodies. Also, update the position of your sprites to correspond to these bodies as you would do for dynamic bodies, but don't set the transformation of your bodies to correspond to their sprites.

CCMenuItemImages positioning?

I am new to cocos2d and I'm trying to build a simple word game. I am stuck with some doubts.
I have arranged the letter's images at bottom of the screen. I've used CCMenuItemImage as buttons and arranged them. No way when I click the images individually, the letters should move to first position and second, and so on. For example:
if there is some letters like b, u, t, x, y, z and if I click on any letters then it should move to some location like (200, 300) (first position) and then second position. Then third... so on.
How should I do it?? I'm a noob so explain properly. Please help!!
Thanks in advance!!
You would want to make your CCMenuItemImage have a selector to target a helper function to help move your CCMenuItemImage. Within the helper function you'd have your CCMenuItemImage moving code.
To move your CCMenuItemImage you can study/copy the cocos2d-iphone project example's ActionsTest.
You can use CCMoveTo or CCMoveBy to move your CCMenuItemImage.
The actions are defined with a duration and a target position. There are some differences between CCMoveTo and CCMoveBy. The significant one is CCMoveBy can be 'reversed' to get a reversed action for your action. Example below moves grossini to ccp(80,80) and the reverse actionByBack moves it back to it's original position. The following code can be found in the ActionsTest.m file of your cocos2d-iphone project. It defines the movement of 3 sprites, tamara, grossini and kathia.
CGSize s = [[CCDirector sharedDirector] winSize];
id actionTo = [CCMoveTo actionWithDuration: 2 position:ccp(s.width-40, s.height-40)];
id actionBy = [CCMoveBy actionWithDuration:2 position: ccp(80,80)];
id actionByBack = [actionBy reverse];
[tamara runAction: actionTo];
[grossini runAction: [CCSequence actions:actionBy, actionByBack, nil]];
[kathia runAction:[ CCMoveTo actionWithDuration:1 position:ccp(40,40)]];
So in your case, if your CCMenuItem is called _alphabet1 you can use the actionBy action definition example to do the following
[_alphabet1 runAction: [CCSequence actions:actionBy, actionByBack, nil]];
That will send your _alphabet1 CCMenuItemImage to ccp(80,80) within 2 seconds and reverse back to the origin in 2 seconds.
If you just want to move your CCMenuItem to a position and not reverse, just use CCMoveTo.

Animating a CCSprite on cocos2d?

Hey guys, I'm new to cocos2d and iPhone development, im currently trying to create a game like "PapiJump",
What I'm currently having problems with, is animating the character CCSprite in my game,
I have created 3 images of my character, character pointing right, left and middle (http://i53.tinypic.com/ngzoyh.png)
so when the character changes its direction (left or right), it wont "jump" directly to the other direction but will animate..
In my code im using the TouchesEnded method, in this method im setting a variable named "touchState",
so if the user touched the right side of the screen it will set "touchState" to 1, otherwise it sets it to 2 (means left).
then in the "init" method i created a "schedule" that runs another method every 0.5 sec that is named: "updateGame",
the "updateGame" method updates the player's position, it works like that:
player.position = ccp(player.position.x , player.position.y - playerGravity.y);
I've read Ray's tutorial on animating CCSprites but i have no idea how to achieve the result that i need..
Thanks in advance and sorry for my bad english!
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 1; i <= 4; ++i)
{
[walkAnimFrames addObject: [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [NSString stringWithFormat:#"spr_fillin_0%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.0333f];
_sprite = [CCSprite spriteWithSpriteFrameName:#"spr_fillin_01.png"];
[_sprite runAction:[CCRepeatForever actionWithAction: [CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]]];
[<CCLAYER OR BATCH NODE> addChild:_sprite];
Edit: Looks like you're talking about just flipping the image around. You can just refetch a sprite with
_sprite = [CCSprite spriteWithSpriteFrameName:#"<New Sprite File>"];
(Or cache them and switch)
Can you clarify your question? If you want to set a different sprite frame, you can use setDisplayFrame:
CCSpriteFrame *spriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:frameName];
[sprite setDisplayFrame:frame];
or if you have an animation:
[sprite runAction:[CCAnimate actionWithAnimation:runAnimation restoreOriginalFrame:NO]];
But I feel like the question is a little vague.
if i got your question properly i can suggest two ways to solve your problem:
first you could rotate your object to till it is upside down, and the continue your previous animations using FlipX(or FlipY) flag marks as true or you can add an animation wich animates only characters rotation and when ever it's finnished change the FLipX(or FlipY) status.