shane shane - 1 year ago 144
Swift Question

Swift Sprite-kit move object

I am using coreMotion to move my main character right now but i am running into device orientation problems after while with this code.

let data = manager.accelerometerData
manager.accelerometerUpdateInterval = 0.0001
(data, error) in
self.plane.physicsBody!.applyForce(CGVectorMake(120.0 * CGFloat((data?.acceleration.x)!), 0))

So My New question is, How can I move my object with a touch on left side of screen or touch on right side of screen, so that the character moves smoothly across and can back and fourth on the x-axis with no problems?

Answer Source

Every SKScene has 4 touches methods (began, ended, moved, cancelled) which you can use.

For example

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
     for touch in touches {
         let location = touch.locationInNode(self)

         if location.x < frame.midX { // left side
              plane.physicsBody?.applyForce(CGVectorMake(-120.0, 0)) // move left
         } else {
              plane.physicsBody?.applyForce(CGVectorMake(120.0, 0)) // move right

Adjust the 120 to a value you like, also depends how big your sprite is.

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download