3

Is there a way of changing a sprites pinned position after it has been set. For example, the below has the 'top' sprite pinned to the 'base' sprite and I want to be able to move the 'top' sprite up and down as required (change the pinned y position). I can see it's easy to rotate the pinned sprite, but moving the position I can't seem to find a solution. I've tried removing the pin (pinned = false), changing the position and then resetting the pin (pinned = true), but the position didn't change (see touches begin section).

Any help or a push in the right direction would be much appreciated, thanks!!!

func generateSprites() {

    // BASE

    let sizeSpriteBase = CGSize(width: 40, height: 36)

    spriteBase = SKSpriteNode(texture: nil, color: UIColor.green, size: sizeSpriteBase)
    spriteBase.position.x = 0
    spriteBase.position.y = 0
    spriteBase.zPosition = 10000
    addChild(spriteBase)

    let physicsBodyBase = SKPhysicsBody(rectangleOf: sizeSpriteBase)
    physicsBodyBase.restitution = 0
    physicsBodyBase.allowsRotation = false
    physicsBodyBase.categoryBitMask = categoryMain
    physicsBodyBase.collisionBitMask = categorySolid
    physicsBodyBase.contactTestBitMask = categorySolid
    spriteBase.physicsBody = physicsBodyBase

    // TOP

    let sizeSpriteTop = CGSize(width: 40, height: 8)

    spriteTop = SKSpriteNode(texture: nil, color: UIColor.orange, size: sizeSpriteTop)
    spriteTop.position.x = 4
    spriteTop.position.y = spriteBase.size.height/2
    spriteBase.addChild(spriteTop)

    let physicsBodyTop = SKPhysicsBody(rectangleOf: sizeSpriteTop)
    physicsBodyTop.pinned = true
    physicsBodyTop.restitution = 0
    physicsBodyTop.allowsRotation = false
    physicsBodyTop.categoryBitMask = categoryMain
    physicsBodyTop.collisionBitMask = categorySolid
    physicsBodyTop.contactTestBitMask = categorySolid
    spriteTop.physicsBody = physicsBodyTop

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    spriteTop.physicsBody?.pinned = false
    spriteTop.position.y -= 8
    spriteTop.physicsBody?.pinned = true

}
Jarron
  • 1,049
  • 2
  • 13
  • 29

1 Answers1

0

Your code looks good, but I think your problem is caused by the gameloop and the way you are changing the physicsbody within TouchesBegan. Touches Began is only acted upon once per game loop. So setting the pinned property to false and then true would equate to just having it set to true.

Instead try setting the pinned property to false and moving the object in the touchesBegan method. Then override the didFinishUpdate method, with something like

if pinned == false { pinned =  true}

Ow and did you set the pinned body to allowRotation = true ! This caught me out before.

Hope this helps

hoboBob
  • 832
  • 1
  • 17
  • 37