Is it possible to detect contact with every frame change when using an animation in SpriteKit?

| | August 4, 2015

Is it possible to detect contact with every frame change when using an animation in SpriteKit? For example, if I have two nodes of a person walking, I want to detect contact with the ground each time the frame changes (the character is walking on a surface). Just can’t seem to get it.

I’ve tried using a for loop to add a physics body and the contact and collision properties to each node, but that doesn’t seem to work. It detects contact once, but that’s it. Anyone have any ideas?

Thanks in advance!

One Response to “Is it possible to detect contact with every frame change when using an animation in SpriteKit?”

  1. Set the Person1 and Person2 SKPhysicsBody a little smaller than the SKSpriteNode.

    Then, add your Person1 and Person2 to update loop. You can do this by subclassing both SKSpriteNodes and then setting the name property to, for example, person. Implement a method in Person1 and Person2 that looks like this:

    //Objective C
    -(void)update:(CFTimeInterval)currentTime
    
    //Swift
    func update(_ currentTime: NSTimeInterval)
    

    Then, in your GameScene – that already has an update: method- use this to call Person1 and Person2 update methods:

    //Objective C
    [self enumerateChildNodesWithName:@"person" usingBlock:^(SKNode *node, BOOL *stop) {
        [(Person *)node update:currentTime];
    }];
    
    //Swift
    self.enumerateChildNodesWithName("person", usingBlock: {
        (node: SKNode!, stop: UnsafeMutablePointer <ObjCBool>) -> Void in 
        var person = node as? Person
        person.update(currentTime)
    })
    

    This will call Persons update: method each frame. Now we want to check in this update: if we are collisioning with the floor, for example, like this:

    //Objective C
    GameScene *parentScene = (GameScene *)self.parent;
    if (CGRectIntersectsWithRect(self.frame, parentScene.floor.frame)){
        //Colliding with the floor.
    }
    
    //Swift
    var parentScene : GameScene = self.parent as? GameScene
    if(CGRectIntersectsRect(_ rect1: parentScene.floor.frame, _ rect2: self.frame){
        //Colliding with the floor.
    }
    

    You don’t really need to call the Person update, you could check the collision in your GameScene's update: method, but it’s always cleaner to subclass and implement it on the other class (or you will end with a really big update).

Leave a Reply