Search code examples
cocos2d-iphonespritebuilder

Magnet effect in Cocos2D


I am trying to create a game that follows the basic principles of electric magnetic field. This involves placing objects on the map that either attracts or repels depending on the charge of the target object. It is 2D and I am wondering if is there anything in the cocos2d library that has magnet effects or anything along the lines of that. The only solution I can think of right now is to calculate the vector effects each object places on the target object during each frame but I feel like that can get very clustered when the number of magnets on the map increases. Any ideas?


Solution

  • Imagine that you have array of 10 bodies and one bigger body as magnet. If magnet body is charged little bodies from array are flying to bigger body. Don't know how it work with spritebuilder, but I think cocos2d+box2d will work for you. Also you can make bodies toggle little bit.

    NSMutableArray *magneticBodies;

    b2Body *magnet;

    if (charged == 1) {
    
        b2Vec2 pos1 = magnet->GetPosition(); 
        float speed = 0.5;   / / You can сhange speed from 0.1 to 1 for slowdown bodies;
    
     for (int i = 0; i < magneticBodies.count; i++) {
    
       b2Body *body = (b2Body*)[[magneticBodies objectAtIndex:i] pointerValue];
    
        b2Vec2 pos2 = body->GetPosition();
    
        b2Vec2 velocity = b2Vec2(pos1 - pos2);
    
        velocity.x = velocity.x*speed;
        velocity.y = velocity.y*speed;
    
        body->SetLinearVelocity(velocity);
    
        }
      }
    

    PS: To get distance between bodies get code from here get distance between two box2d