Search code examples
iosswiftrotationaccelerometercore-motion

How to rotate sprite based on phone rotation


I am trying to rotate a sprite based on the iPhone's rotation (roll). How would I go by doing this in swift (4.2)? I found Apple documentation using CMAttitude, but I don't understand how to implement this into code. Any help is appreciated, Thanks!!!


Solution

  • "You access CMAttitude objects through the attitude property of each CMDeviceMotion objects passed to an application."

    See the official documentation

    Have a look at CMDeviceMotion - that is what is really necessary!

    You need the CMMotionManager to receive what you want.
    Maybe is this link or this tutorial helpful for you.
    -> everything you need to know, to get started with DeviceMotions

    Additional:
    Think you re at SKit, that has the function rotate.

    Simple as that:
    based on the rotation of the phone you could
    - start rotation clockwise or counterclockwise
    - stop the rotation
    - and even change the rotation

      let angle : Float = (direction == yourDirection) ? Float(X) : -Float(X)
      let rotate = SKAction.rotateByAngle(angle, duration: 1)
      let repeatAction = SKAction.repeatActionForever(rotate)
      sprite.runAction(repeatAction, withKey: "rotate")