Search code examples
sprite-kitintersectiontouchesbegan

SpriteKit Jumping when hitting Ground


So I got 2 SKSpriteNodes, a Human and a Block. If the Human hits the block on the top, it should be able to jump, if he is in the air, he shouldn't. I am using intersectsNode, but then the Human only jumps at the end of the Block, and I don't really know why. A Member of the Forum told me to use bodyAtPoint, but if I use it it only shows : "there is no visible @interface for SKSpriteNode declares the selector bodyAtPoint".

My current Code with intersectsNode :

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

Human.physicsBody.velocity = CGVectorMake(0, 0);
if([Human intersectsNode:Block1]){
[Human.physicsBody applyImpulse:CGVectorMake(0, 40)];
}

Solution

  • I suggest you use the didBeginContact: instead of intersectsNode. In MyScene you can set it up like this:

    @implementation MyScene
    {
        BOOL playerBlockContact
    }
    
    - (void)didBeginContact:(SKPhysicsContact *)contact
    {
        uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
    
        if (collision == (CNPhysicsCategoryPlayer | CNPhysicsCategoryBlock))
        {
            playerBlockContact = true;
            NSLog(@"Contact");
        }
    }
    
    - (void)didEndContact:(SKPhysicsContact *)contact
    {
        uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask);
        if (collision == (CNPhysicsCategoryPlayer | CNPhysicsCategoryBlock))
        {
            playerBlockContact = false;
            NSLog(@"Contact lost");
        }
    }
    

    Then replace your if([Human intersectsNode:Block1]) with If(playerBlockContact).