Search code examples
iphonecocos2d-iphonephysicsgame-physics

how to change the speed of moving box2d object in cocos2d after touch on ccsprite


enter image description herei am working on a ios game by using cocos2d . in my scene clouds are moving right to left direction with different vilocity. 1)i just want when user tap on a cloud it moves more fast left to right. 2)when clouds will go outside of view then it again appear from left side and start moving to left in normal speed.


Solution

  • 1.) Detect the cloud the user touched, the increase the speed of the body. To immediately increase the speed, set the linear velocity of b2body associated with cloud. To gradually increase speed, apply a force/impulse. For example:

    in ccTouchesBegan

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
    for(Cloud *cloud in clouds) {
    
       if (CGRectContainsPoint( cloud.boudingBox, location )) {
    
          b2Body *b = cloud.b2Body;
          b2Vec2 *currentVelocity = b->GetLinearVelocity();
          b2Vec2 *newVelocity = b2Vec2(currentVelocity.x + addToSpeed, currentVelocity.y);
          b->SetLinearVelocity( newVelocity );
    
       }
    
    }
    

    2.) Detect when the cloud b2body position has moved outside the view in the update method. Then you can either destroy the cloud body with sprite and create a new one in the desired position, or use b2Body->SetTransform() to move the body to the new location with SetLinearVelocity( startingSpeed)