SpriteKit: how to simulate magnetic force

I am developing a game using iOS SpriteKit. I am trying to make an object in this game that will pull objects on it, and the force will increase as objects get closer to it, think of a magnet or a black hole. It was difficult for me to determine what properties needed to be changed in order to make these physicalBody nodes attract other nodes as they passed.

+3
source share
3 answers

In iOS 8 and OS X 10.10, SpriteKit has SKFieldNodeto create forces that apply to bodies in the area. This is great for things like buoyancy, specific gravity and magnets.

, - magneticField, , , , "" . , .. , . , - , , - - .

, - ( ) , radialGravityField - , . ( , categoryBitMask fieldBitMask , / .)

, , , , electricField - . charge , ( ) ( ) .


iOS 8 OS X 10.10 SpriteKit .

. update: , ( , ), .

+16

,

-(void)didSimulatePhysics
{
  [self updateCoin];
}

-(void) updateCoin
{
    [self enumerateChildNodesWithName:@"coin" usingBlock:^(SKNode *node, BOOL *stop) {
        CGPoint position;
        position=node.position;
        //move coin right to left
        position.x -= 10;
        node.position = position;
        //apply the magnetic force between hero and coin
        [self applyMagnetForce:coin];
        if (node.position.x <- 100)
            [node removeFromParent];

    }];
}

-(void)applyMagnetForce:(sprite*)node
{
    if( gameViewController.globalStoreClass.magnetStatus)
    {
        //if hero under area of magnetic force
        if(node.position.x<400)
        {
            node.physicsBody.allowsRotation=FALSE;
            ///just for fun
            node.physicsBody.linearDamping=10;
            node.physicsBody.angularVelocity=10*10;
            //where _gameHero is magnet fulling object
            [node.physicsBody applyForce:CGVectorMake((10*10)*(_gameHero.position.x-      node.position.x),(10*10)*(_gameHero.position.y-node.position.y)) atPoint:CGPointMake(_gameHero.position.x,_gameHero.position.y)];

        }
    }
}

,

+2

Well, it looks like you can now since Apple introduced SKFieldNode in iOS 8.

+1
source

All Articles