cocos2d-JS 实现横竖屏切换时的提示效果
cocos2d-JS 实现 横竖屏提示 :
效果 :
-
竖屏 :
-
横屏 :
全局添加创建提示层方法 :
//创建旋转提示层 var createColorLayer = function(){ var rotateImg = new cc.Sprite("res/rotate.png"); rotateImg.setPosition(cc.winSize.width/2 , cc.winSize.height/2); var layer = new cc.LayerColor(cc.color(0,0,0,255), cc.winSize.width + 100, cc.winSize.height + 100 ); layer.addChild(rotateImg); return layer; };
全局添加旋转屏幕帧听 :
//屏幕旋转回调 window.addEventListener('orientationchange', function(event) { var currentScene = cc.director.getRunningScene(); //当前场景 if(currentScene == null) return; if (window.orientation == 180 || window.orientation == 0) //竖屏 - 创建旋转提示层 { //alert("竖屏"); var LayerColor = createColorLayer(); currentScene.addChild(LayerColor,9999,1002); //添加tag值 1002 } if(window.orientation == 90 || window.orientation == -90) //横屏 - 移除 { //alert("横屏"); var first = currentScene.getChildByTag(1001); //通过tag值 寻找对应层 if(first != null) { first.removeFromParent(); } var second = currentScene.getChildByTag(1002); if(second != null) { second.removeFromParent(); } } });
初始化游戏场景时调用
全局帧听需要屏幕旋转才会生效,所以第一次需要手动添加提示旋转 .
//竖屏显示提示 var showRotate = function(Scene){ if (screen.height > screen.width) { var LayerColor = createColorLayer(); Scene.addChild(LayerColor,9999,1001); //添加tag值 1001 } };
JavaScript 判断是否为移动设备 :
function IsMobile() { var userAgentInfo = navigator.userAgent; var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"]; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > -1) { return true; } } return false; }
JavaScript 判断是不是竖屏 , 创建显示 提示 .
//竖屏显示提示 var showRotate = function(Scene){ if(IsMobile()) { var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; cc.log("宽度 = "+ w + " | 高度 = "+h); if (h >= w) { var LayerColor = createColorLayer(); Scene.addChild(LayerColor,9999,1001); //添加tag值 1001 //cc.director.pause() } } };