How to move the PhysicsSprite in box2d - ios5

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.

Related

Move SKSpriteNode with Physics

I am trying to move an SKSpriteNode with physics by setting it's velocity. I am doing this on top of another SKNode (the map) that is part of the SKScene. Positions of "cities" are stored in custom Location objects.
I know the location of the initial SKSpriteNode (the ship) and I know the desired location. From what I've read, I can move the sprite by setting it's velocity. I do so like this:
float dy = _player.desiredLocation.yCoordinate - _mapNode.pin.position.y;
float dx = _player.desiredLocation.xCoordinate - _mapNode.pin.position.x;
_mapNode.pin.physicsBody.velocity = CGVectorMake(dx, dy);
This is all inside the didSimulatePhysics function inside the SKScene. Once the user taps a Location, I find the position and set the velocity. This seems to work well the FIRST time, but the sprite moves all over the place in subsequent times. Any idea what could be going wrong here?
PS: Setting skView.showsPhysics = YES; puts the circle of the physics body way off the position of the sprite.
In the map node:
self.pin = [SKSpriteNode spriteNodeWithImageNamed:[IPGameManager sharedGameData].world.player.ship.type];
self.pin.userInteractionEnabled = NO;
self.pin.position = CGPointMake([IPGameManager sharedGameData].world.player.location.xCoordinate, [IPGameManager sharedGameData].world.player.location.yCoordinate);
self.pin.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:10.0];
self.pin.physicsBody.dynamic = YES;
self.pin.physicsBody.allowsRotation = NO;
self.pin.physicsBody.friction = 0.0;
self.pin.physicsBody.linearDamping = 0.0;
[self addChild:self.pin];

Reanimating a bouncing ball in sprite-kit

Reanimating a bouncing ball in sprite-kit
I have a question about the best way to reanimate a bouncing ball. Using Ray Wenderlich's tutorial on building a break out game as a reference I have a number of circular shape nodes which continually bounce around a gravity-less environment. When the user touches one of them, it centers on the screen, stops moving, and transforms into something else. When the user touches it again, it is supposed to transform back into the circular shape node and then continue bouncing around the screen.
I have it all working as I like except for reanimating the ball. The manner in which I stop the animation is simply to set the physicsBody to nil. Once I want to reanimate, I call the method that sets up the physicsBody for the node and I apply an impulse to it. But frustratingly, the impulse does not have the effect I think it should. Clearly, my expectations are incorrect.
Here is the code in question:
- (void)applyPhysics
{
// Set physics properties
self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:self.frame.size.width/2];
self.physicsBody.friction = 0.0f;
self.physicsBody.restitution = 1.0f;
self.physicsBody.linearDamping = 0.0f;
self.physicsBody.allowsRotation = NO;
self.physicsBody.collisionBitMask = wallCategory;
self.physicsBody.categoryBitMask = bubbleCategory;
}
- (void)morphPicker
{
BOOL check = NO;
if (check) NSLog(#"morphPicker called.");
[self runAction:[SKAction fadeAlphaTo:0.0 duration:.5]];
if (self.flipped) {
if (check) NSLog(#"The information side is showing.");
self.fillColor = bubbleColors[self.index % bubbleColors.count];
self.alpha = .9;
// Resume physics:
[self applyPhysics];
[self.physicsBody applyImpulse:CGVectorMake(10.0f, -10.0f)];
} else {
// stop physics:
self.physicsBody = nil;
if (check) NSLog(#"The statistic side is showing.");
self.fillColor = [SKColor blackColor];
self.alpha = .9;
[self transformToPickerNode];
[self removeAllChildren];
}
self.flipped = !self.flipped;
}
So my questions are these:
How should I be reanimating the ball if applying an impulse to it is not the correct method?
Is there a more elegant way to stop the animation after centering the node than setting the physicsBody to nil? Even to my novice instincts it feels like a brutish method.
After all my trials and searching for an answer to this I firmly believe that there is no elegant way to apply a new impulse to a sprite and expect it to move in the physics world. Thus my answer must be "it cannot be done at this point." However, my solution of removing all the the animated sprites from the scene and recreating them turned out to be the best solution for a completely different reason. The nature of my physics world caused my "floating bubbles" to eventually end up in the corners of the scene where they remained unmoving. Occasionally removing and recreating them had the effect of sending them happily bouncing around the scene again :)

Collision of Sprites in CCSpriteBatchNode and CCParallaxNode

I have two sprites one is added as the child of CCSpriteBatchNode and the other as the child of CCParallaxNode. Is there any method to detect their collision? I have used the following code.
-(void)CheckCollition:(CCSprite *)Opp_Obs Opponent:(CCSprite *) H_man
{
// NSLog(#"inside check collision");
CGRect b_rect=[Opp_Obs boundingBox];
CGPoint p_position=[H_man position];
if (CGRectContainsPoint(b_rect,p_position))
{
NSLog(#"collision with opponent");
// Zoom Animation with Points
CCScaleBy *zzomscal=[CCScaleTo actionWithDuration:.2 scale:.12];
CCRotateTo * rotLeft = [CCRotateBy actionWithDuration:0.2 angle:360];
CCCallFunc *ccfun=[CCCallFunc actionWithTarget:self selector:#selector(zoomComplete)];
CCSequence * zzomseq = [CCSequence actions:zzomscal,rotLeft,ccfun, nil];
[H_man runAction:zzomseq];
}
else
{
NSLog(#"no collision");
}
}
But here the control never enters into the loop. Is there any other solution? Anyone please help me.
Set a breakpoint and compare the values of rect and position. One of them may be zero, or way off.
In the latter case you may need to convert the bbox origin and position to world coordinates first in order to compare them. This is the case when the sprites' parents are moving too (parent position != 0,0).

b2Body questions

I have 2 questions with b2Body:
What is the difference between b2Body and b2BodyDef?
How would I add a b2Body to a CCScene with coordinates from a CGRect which I already have coded? Also how would I add userData to it so I can keep a reference to this?
Thanks!
A b2BodyDef is used to define information about a body as a whole, such as position and rotation. Compared to the other information you require for a b2Body, such as friction and resititution, that is defined on a per fixture basis using b2Fixtures. The b2Body is an amalgamation of a body definition and at least one fixture.
With regard to creating the body from a predefined rect, I'd advise using setAsBox: assuming you are using a b2PolygonShape.
The way I usually accomplish the joining of the two is to create a class called BodyNode which has ivars of a b2Body and a CCSprite. Assign either the BodyNode, i.e. self or the sprite as the userData and update them as follows:
-(void) onEnter
{
[self scheduleUpdate];
[super onEnter];
}
-(void) update:(ccTime) dt
{
//Update the position of the sprite to the position of the body
//Update the rotation of the body to the rotation of the sprite. Take care to note that the rotation of the sprite is in degrees whereas the rotation of the body is in radians.
}

How do I animate a sprite using cocos2d?

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