web:

web修改就比较简单了,直接调用cocos creater内置方法:cc.view.getFrameSize() 获取视图中边框尺寸,把宽和高交换一下就可以了,如下:

 changeOrientation:function(){
    let w = cc.view.getFrameSize().width;
    let h = cc.view.getFrameSize().height;
    cc.view.setFrameSize(h,w);
}

android和ios的就比较麻烦了,需要调用原生来修改,js如下:

js:
 changeOrientationH:function(isH){
    let w = cc.view.getFrameSize().width;
    let h = cc.view.getFrameSize().height;
    cc.view.setFrameSize(h,w);
    if (cc.sys.os == cc.sys.OS_IOS) {
        console.log("ios:");
        jsb.reflection.callStaticMethod('AppController',"changeOrientationH",isH);
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        console.log("android:");
        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "changeOrientationH", "(Z)V", isH);
    } 
}

Android:

// 设置屏幕方向
public static void changeOrientationH(boolean isH) {
    if (isH) {
        instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Log.d("横屏>>>>>", "SCREEN_ORIENTATION_LANDSCAPE: ");
    }else{
        instance.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Log.d("竖屏>>>>>", "SCREEN_ORIENTATION_LANDSCAPE: ");
    }
}

IOS:

AppComtorller.mm加这个函数

// 设置屏幕方向
+(void) setOrientation:(NSNumber *) orientation {
    NSNumber *orientationTarget;
    NSNumber * landscape = [NSNumber numberWithInt:1];
    NSNumber * portrait = [NSNumber numberWithInt:2];
    if ([orientation isEqualToNumber:landscape]) {
    orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    } else if ([orientation isEqualToNumber:portrait]){
    orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
    }
}

RootViewController.mm

+(void) setCurOrientation:(NSNumber * ) orientation {
    curOrientation = orientation;
}
// For ios6, use supportedInterfaceOrientations & shouldAutorotate instead
//这是修改原来的函数,不是新加的
(NSUInteger) supportedInterfaceOrientations{
    NSNumber * landscape = [NSNumber numberWithInt:1];
    if ([curOrientation isEqualToNumber:landscape]) {
        return UIInterfaceOrientationMaskLandscape;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
//return UIInterfaceOrientationMaskAllButUpsideDown;
//return UIInterfaceOrientationMaskLandscape;
}
Logo

这里是一个专注于游戏开发的社区,我们致力于为广大游戏爱好者提供一个良好的学习和交流平台。我们的专区包含了各大流行引擎的技术博文,涵盖了从入门到进阶的各个阶段,无论你是初学者还是资深开发者,都能在这里找到适合自己的内容。除此之外,我们还会不定期举办游戏开发相关的活动,让大家更好地交流互动。加入我们,一起探索游戏开发的奥秘吧!

更多推荐