1
votes

If declare 2 object (example Rectangle and Triangle) with physicsBody, can drag and drop them, how can we set, when we drag one close to another, 2 object will connect at any suitable point?

2

2 Answers

0
votes

In your touchesEnded (drop event), check the locations of your two objects and, if they are close enough, add a joint.

0
votes

You can create a physicsBody that is larger than your sprite and test if it makes contact with another body in didBeginContact. With the SKPhysicsContact object, you can join the two physics bodies at the contact point with an SKPhysicsJointFixed or SKPhysicsJointLimit.

EDIT: Here's an example of how to join two sprites that touched:

Declare an instance variable for the node that is selected.

{
    SKSpriteNode *selectedNode;
}

Join two physics bodies if a contact is detected. The nodes are connected with an SKPhysicsJoint.

- (void) didBeginContact:(SKPhysicsContact *)contact
{
    if ((contact.bodyA.categoryBitMask == category1
                    && contact.bodyB.categoryBitMask == category2)
                    || (contact.bodyB.categoryBitMask == category1
                    && contact.bodyA.categoryBitMask == category2)) {
        CGPoint point = contact.contactPoint;
        SKPhysicsJoint *joint = [SKPhysicsJointFixed jointWithBodyA:contact.bodyA bodyB:contact.bodyB anchor:point];
        [self.physicsWorld addJoint:joint];
    }
}

Select and move sprite with based on touch.

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

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];

        SKNode *node = [self nodeAtPoint:location];
        selectedNode = (SKSpriteNode *)node;
    }
}

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

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];

        selectedNode.position = location;
    }
}

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

    selectedNode = nil;
}