1
votes

I'm kind of new with SpriteKit and I'm having some troubles with the physics, I've tried many things to make a SKSpriteNode move with a force or an impulse but it never moves, only gravity affects it when i set it.

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        self.anchorPoint = CGPointMake(0.5, 0.5);
        myWorld = [SKNode node];
        [self addChild:myWorld];

        SKSpriteNode* map = [SKSpriteNode spriteNodeWithImageNamed:@"grass"];
        [myWorld addChild:map];

        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:map.frame];
        self.physicsBody.friction = 0.0f;
        self.physicsBody.categoryBitMask = 2;
        self.physicsWorld.gravity = CGVectorMake(0.0, 0.0);
        self.physicsWorld.contactDelegate = self;

        pointOfView = [SKSpriteNode spriteNodeWithColor:[UIColor colorWithWhite:1 alpha:0.2] size:CGSizeMake(300, 548)];
        [myWorld addChild:pointOfView];

        pointOfView.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:pointOfView.frame.size];
        pointOfView.physicsBody.friction = 0.0f;
        pointOfView.physicsBody.restitution = 1.0f;
        pointOfView.physicsBody.linearDamping = 0.0f;
        pointOfView.physicsBody.allowsRotation = NO;
        pointOfView.physicsBody.collisionBitMask = 2;
        pointOfView.physicsBody.categoryBitMask = 3;
        [pointOfView.physicsBody applyImpulse:CGVectorMake(10.0f, -10.0f)];
    }
    return self;
}

Here is most of my code in my main scene, there's nothing else except some empty methods like update or touchesBegan.. Am I missing something ? I've tried so many things, i'm starting to lose it haha

Thanks very much for any help !

3
you have written wrong code your pointOfView no affected by gravity you are just applying a small impusle on it. - dragoneye

3 Answers

1
votes

It's a bit late, but the answer is here: Not able to apply impulse to SKSpriteNode physics body

The problem is that you've created a physics body with bodyWithEdgeLoopFromRect; this creates a static physics body which won't respond to applyImpulse. You need to add the physics body using bodyWithRectangleOfSize: instead.

0
votes
pointOfView.physicsBody.dynamic = YES;

The dynamic property decides if a sprite should be affected by physics forces.

-1
votes

you have written wrong code your pointOfView not affected by gravity you are just applying a small impusle on it.

change this line self.physicsWorld.gravity = CGVectorMake(0.0, 0.0) to self.physicsWorld.gravity = CGVectorMake(0.0, -9.8); if u looking for negative gravity towards up direction and CGVectorMake(0.0, 9.8) if you looking for positive gravity towards downwards. and try to apply impulse after a interval [pointOfView.physicsBody applyImpulse:CGVectorMake(10.0f, -10.0f)];