Search code examples
androidc++iphonecocos2d-x

How to get device orientation


What is the best way to get the device orientation with cocos2d-x (c++)?

My Android/iOS application does support all 4 device orientations, and more important than knowing if it is landscape or portrait, I would like to know if it is upside down or not.

I will have to know from within a CCLayer.

UPDATE

I am trying to get events for right tilt and left tilt. To do so, I am calculating the angle at which the device is held. However, I need to know what orientation the device has, to be able to know if I am actually tilting left or right.


Solution

  • Though cocos2d-x is cross platform, few things are still very much platform dependent, for example, if you see the CCFileUtils, we have separate implementation files for iOS, Android etc, the cross platform is maintained with a single header,

    Keeping that in mind,

    In Android, you can get the device orientation by using the constants,

    Surface.ROTATION_0 (no rotation)
    Surface.ROTATION_90
    Surface.ROTATION_180
    Surface.ROTATION_270. 
    

    which you can get by calling Display.getRotation() (It only rotate in all these directions if, android:screenOrientation:fullSensor is set)

    And in iOS, You can get the values with

    UIDeviceOrientationPortrait
    UIDeviceOrientationPortraitUpsideDown
    UIDeviceOrientationLandscapeLeft
    UIDeviceOrientationLandscapeRight
    

    (It only rotates in all these directions if, supportedInterfaceOrientations method returns UIInterfaceOrientationMaskAll)

    Note: Its not a good practice to rotate a phone upside down in portrait mode, only on tablets its accepted.. (Apple might even reject your app for this reason)

    Let me know if you want to know how to use it, but googling the keywords will give you the usage..