Cocos2d Box2d how to shoot an object inside the screen
- by Ahoura Ghotbi
I have the code below :
- (id) initWithGame:(mainGame*)game {
if ((self = [super init])) {
isTouchEnabled_ = YES;
self.game = game;
CGSize size = [[CCDirector sharedDirector] winSize];
screenH = size.height;
screenW = size.width;
character = [CCSprite spriteWithFile:@"o.png"];
character.position = ccp( size.width /2 , size.height/2 );
character.contentSize = CGSizeMake(72, 79);
[self addChild:character z:10 tag:1];
_body = NULL;
_radius = 14.0f;
// Create ball body and shape
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
ballBodyDef.userData = character;
_body = _game.world->CreateBody(&ballBodyDef);
b2CircleShape circle;
circle.m_radius = 26.0/PTM_RATIO;
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 1.0f;
ballShapeDef.friction = 0.2f;
ballShapeDef.restitution = 0.8f;
_body->CreateFixture(&ballShapeDef);
[self schedule:@selector(gameChecker:)];
[self schedule:@selector(tick:)];
}
return self;
}
- (void)gameChecker:(ccTime) dt{
if(character.position.y > 200){
[self unschedule:@selector(tick:)];
[self schedule:@selector(dropObject:)];
}
}
- (void)tick:(ccTime) dt {
b2Vec2 force;
force.Set(_body->GetLinearVelocity().x, _body->GetLinearVelocity().y+1.0f);
for (b2Body* b = _game.world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() == character)
{
b->SetLinearVelocity(force);
}
}
_game.world->Step(dt, 10, 10);
for(b2Body *b = _game.world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *ballData = (CCSprite *)b->GetUserData();
ballData.position = ccp(b->GetPosition().x * PTM_RATIO,
b->GetPosition().y * PTM_RATIO);
ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
-(void)dropObject:(ccTime) dt{
b2Vec2 force;
force.Set(_body->GetLinearVelocity().x, _body->GetLinearVelocity().y-1.0f);
for (b2Body* b = _game.world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() == character)
{
b->SetLinearVelocity(force);
}
}
_game.world->Step(dt, 10, 10);
for(b2Body *b = _game.world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *ballData = (CCSprite *)b->GetUserData();
ballData.position = ccp(b->GetPosition().x * PTM_RATIO,
b->GetPosition().y * PTM_RATIO);
ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
I have been trying to get the effect that fruit ninja has when shooting the fruits. but it seems like its hard to get such animation so I was wondering if anyone can point me to the right direction and/or give me a sample code for a single object that gets thrown into the screen with a direction.