How to connect two SKSpriteNode using SKPhysicsJointPin - swift

I am trying to connect two SKSpriteNode using SKPhysicsJointPin in anchorPoint , marked as a green dot in the screenshot below. Later, I would like to include physicsBody!.dynamic = true in object2 to get the "swing animation" of object2.

enter image description here

enter image description here

I am having difficulty right from the start when creating SKPhysicsJointPin , even if I don't get an error in Xcode, it does not compile.

Here is the code:

 import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { let object1 = SKSpriteNode(imageNamed: "white") let object2 = SKSpriteNode(imageNamed: "black") override func didMoveToView(view: SKView) { // Setup background image self.backgroundColor = UIColor(hex: 0x60c0f3) // Setup physics body to the scene (borders) self.physicsBody = SKPhysicsBody (edgeLoopFromRect: self.frame) // Change gravity settings of the physics world self.physicsWorld.gravity = CGVectorMake(0, -9.8) self.physicsWorld.contactDelegate = self //=========================================== // White object properties object1.physicsBody = SKPhysicsBody(rectangleOfSize: object1.frame.size) object1.physicsBody!.dynamic = false object1.position = CGPointMake(size.width/2 - object1.size.width/2, size.height/2) // Black object properties object2.physicsBody = SKPhysicsBody(rectangleOfSize: object2.frame.size) object2.physicsBody!.dynamic = true object1.anchorPoint = CGPointMake(0, 0) object2.position = CGPointMake(size.width/2 + object2.size.width + 2, size.height/2 + object2.size.height/2) // Create joint between two objects var myJoint = SKPhysicsJointPin.jointWithBodyA(object1.physicsBody, bodyB: object2.physicsBody, anchor: CGPoint(x: CGRectGetMaxX(self.object1.frame), y: CGRectGetMaxY(self.object2.frame))) self.physicsWorld.addJoint(myJoint) self.addChild(object1) self.addChild(object2) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } } 

Xcode error I get enter image description here

Please report what is wrong in my code. Thanks.

+5
source share
1 answer

Two questions: 1) you need to add nodes containing physical bodies to the scene before they connect to the joint, and 2) you need to connect nodes with a minimum value of Y not at most (if you want to behave as shown in diagram), since the scene origin is the bottom / left viewing angle, and positive Y is up.

  // Do this prior to adding the joint to the world self.addChild(object1) self.addChild(object2) // Create joint between two objects. Edit: changed MaxY to MinY to attach bodies // at bottom of the nodes var myJoint = SKPhysicsJointPin.jointWithBodyA(object1.physicsBody, bodyB: object2.physicsBody, anchor: CGPoint(x: CGRectGetMaxX(self.object1.frame), y: CGRectGetMinY(self.object2.frame))) self.physicsWorld.addJoint(myJoint) 
+2
source

Source: https://habr.com/ru/post/1203314/


All Articles