Search code examples
ios7sprite-kitphysicsgame-physicsskphysicsbody

SpriteKit physics body returning to original vertical position after hit/knock


I'm trying to make a physics mechanic where a vertically standing object can be hit or knocked down and then will pivot back up to it's origin position. Think of it like a floor mounted punch bag. So the object will have a low pivot/anchor point.

I just wanted a little theoretical direction in how to approach this using SpriteKit physics.

Any help would be really appreciated.

Thanks


Solution

  • The following creates a composite object by joining two bodies: a circle and a weight. The weight is offset relative to the center of the circle and is much denser. When added to the scene, gravity rotates the combined object so the side with the weight is on the bottom. To use it 1) create a new sprite kit game, 2) replace the default initWithSize and touchesBegan methods with this code, and 3) run and click at various locations in the scene.

    -(id)initWithSize:(CGSize)size {    
        if (self = [super initWithSize:size]) {
            /* Setup your scene here */
    
            self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
    
            self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];
    
        }
        return self;
    }
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
        for (UITouch *touch in touches) {
            CGPoint location = [touch locationInNode:self];
            SKShapeNode *circle = [SKShapeNode node];
            circle.path =[UIBezierPath bezierPathWithOvalInRect: CGRectMake(-32, -32, 64, 64)].CGPath;
            circle.position = location;
            circle.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:32];
    
            SKSpriteNode *weight = [SKSpriteNode spriteNodeWithColor:[UIColor whiteColor] size:CGSizeMake(8, 8)];
            // Adjust this to get the desire effect
            weight.position = CGPointMake(location.x+1, location.y+28);
            weight.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:4];
            // Adjust this to get the desired effect
            weight.physicsBody.density = 100.0;
    
            // The physics bodies must be in the scene before adding the joint
            [self addChild:circle];
            [self addChild:weight];
    
            // Join the circle and the weight with a physics joint
            SKPhysicsJoint *joint = [SKPhysicsJointFixed jointWithBodyA:circle.physicsBody bodyB:weight.physicsBody anchor:weight.position];
            [self.physicsWorld addJoint:joint];
        }
    }