TAGS :Viewed: 7 - Published at: a few seconds ago

[ Move SKPhysicsBody with device tilt swift ]

I have an image on the screen that is an SKSpriteNode with an SKPhysicsBody attached to it. I'm trying to move it around on the screen via tilting of the device. I have it moving along the x-axis but I cant seem to get it to move along the y-axis.

I used parts of this tutorial to get to the point I'm at. I used the part about the user ship to get my image to move along the x-axis.

http://www.raywenderlich.com/76740/make-game-like-space-invaders-sprite-kit-and-swift-tutorial-part-1

func processUserMotionForUpdate(currentTime: CFTimeInterval) {
    let ship = childNodeWithName(kShipName)

    if let data = motionManager.accelerometerData {
        if (fabs(data.acceleration.x) > 0.2) {
            ship!.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.x), 0))
        }
        if (fabs(data.acceleration.y) > 0.2) {
            ship!.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.y), 0))
        }

    }
}

That if statement with the y is the part I added to try to move the image up and down, however it isn't working.

Is there a mistake in the logic here? Or am I just going about this the wrong way?

Answer 1


When you create the Vector to apply the force for the y-Axis, you pass the y-parameter to the x-axis. To solve this, you have to swap the parameters in the second applyForce-statement:

if (fabs(data.acceleration.y) > 0.2) {
    ship!.physicsBody!.applyForce(CGVectorMake(0, 40.0 * CGFloat(data.acceleration.y)))
}