Search code examples
collision-detectionsprite-kittouchesbegan

SpriteKit Collision jumping


I got 2 objects, a Human and a Block. If the Human is on the Block, he is able to jump, if he is in the air, he isn't. How can I code that, cause the CGRectIntersectsRect doesn't work in SpriteKit for me.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent )event { / Called when a touch begins */

Human.physicsBody.velocity = CGVectorMake(0, 0);

[Human.physicsBody applyImpulse:CGVectorMake(0, 40)];

}

I got the Block and the Human already in Categorys, for Collision detection :

else if ((firstBody.categoryBitMask & HumanCategory) != 0 &&
         (secondBody.categoryBitMask & BlockCategory) != 0)
{

}

Should I use that somehow for the code? Thanks for helping.


Solution

  • To prevent jumping when not touching the ground use bodyAtPoint: to detect whether or not there is any physics body directly underneath your node.

    If it is possible that there will be multiple physics bodies under your character that may not be relevant you can use enumerateBodiesAtPoint:usingBlock: to make sure you only allow jumping when the physics bodies associated node is a Block.

    Update:

    These methods are available on the SKPhysicsWorld class you can access the instance via the physicsWorld property on your scene.

    //Please note that this point is in the scenes coordinate system
    CGPoint thePointDirectlyBelowMyNode = ...;
    [scene.physicWorld bodyAtPoint:thePointDirectlyBelowMyNode];