0

I'm trying to make an air hockey game using SpriteKit. I trying to make the pucks draggable but I can't make them continue to move after the touch has ended. Right now I am binding the touch and the puck and setting it's position when the touch moves.

using the physics system:

override func update(currentTime: NSTimeInterval) {
        for (touch, node) in draggingNodes {
            let targetPosition = touch.locationInNode(self)
            let distance = hypot(node.position.x - targetPosition.x, node.position.y - targetPosition.y)
            var damping = sqrt(distance * 100)
            if (damping < 0) {
                damping = 0.0
            }
            node.physicsBody!.linearDamping = damping
            node.physicsBody!.angularDamping = damping
            let translation = CGPointMake(targetPosition.x - node.position.x, targetPosition.y - node.position.y)
            node.physicsBody!.velocity = CGVectorMake(translation.x * 100, translation.y * 100);
        }
    }
J Doe
  • 29
  • 3
  • Did you try this on a device? The simulator isn't the best for testing this type of behavior. – 0x141E Aug 04 '15 at 20:33
  • tried on simulator, I don't have an iOS developer account and I am using xcode 6.x – J Doe Aug 04 '15 at 20:48
  • 1
    You may find this useful http://stackoverflow.com/questions/28245653/how-to-throw-skspritenode – 0x141E Aug 04 '15 at 21:33
  • It worked! thank you. post it as an answer so I can give you points :D – J Doe Aug 04 '15 at 21:50
  • @JDoe Thank you for the code you provided in your question! It helped me with a problem of my own! – STO Jul 07 '18 at 12:51

1 Answers1

1

You're likely going to need to do a lot more reading. Either you'll use the physics system:

In which case you'll impart an impulse onto the puck on the touch end event, having calculated the speed based on a delta in position and delta in time from last frame to current frame (or some type of average over more than 1 frame). https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Physics/Physics.html

[OR]

You'll manually set velocity on the puck (not using the physics system), and then manually update the puck's position per frame based on that velocity, then recalculate its vector when it comes into contact with another object based on angle of of incidence.

Cooper Buckingham
  • 2,503
  • 2
  • 15
  • 23
  • I'm using the physics system. the problem is that after the touch end the puck stops moving or comeback to the last position. – J Doe Aug 04 '15 at 17:02
  • i tried but it didn't work(didn't continue) so i came back to just setting the position – J Doe Aug 04 '15 at 17:03
  • That's because you are manually setting its position. So read the first part of my answer that talks about having to set an impulse on the physics body based on calculating a vector from previous frames. – Cooper Buckingham Aug 04 '15 at 17:03