码迷,mamicode.com
首页 > 移动开发 > 详细

移动端html5重力感应

时间:2015-10-27 17:04:42      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

下面是测试案例,只测试过itouch,iphone
http://06wjin.sinaapp.com/billd/    
http://06wjin.sinaapp.com/billd/test.html
重力感应主要用到两种事件:
1 orientationchange
     这个事件在屏幕发生翻转时触发
     window.orientation可获得设备的方向,一共有三个值0:竖直,   90:右旋,   -90:左旋
deviceorientation 和 MozOrientation(firefox专用)
deviceorientation事件可获得三个值alpha,beta,gamma,分别代表绕Z轴的旋转角度(0~360),绕X轴的旋转角度(-180~180),绕Y轴的旋转角度(-90~90)
MozOrientation事件中可获得三个值z,x,y,分别代表垂直加速度,左右的倾斜角度,前后的倾斜角度(取值范围:-1~1)
 
坐标系见下图
 技术分享
 
下面是示例游戏用到重力感应的代码:
window.onorientationchange = function(e){
     game.hideNavBar();   //屏幕翻转时隐藏地址栏
     if(game.stage) game.stage.updatePosition(); //更新舞台位置
};

window.ondeviceorientation =  function(e) 
{
    var ang;
    var o = window.orientation;  //获取设备方向
    if(o == 90){
        ang = e.beta;  //设备横向1
    }
    else if(o == -90){
        ang = -e.beta;  //设备横向2
    }
    else if(o == 0){
        ang = e.gamma;    //设备纵向
    }

    if(ang > 5) 
    {
        keyState[Q.KEY.RIGHT] = true;
    }
    else if(ang < -5) 
    {
        keyState[Q.KEY.LEFT] = true;
    }
    else
    {
        keyState[Q.KEY.RIGHT] = false;
        keyState[Q.KEY.LEFT] = false;
    }
}

移动端html5重力感应

标签:

原文地址:http://www.cnblogs.com/mrjie/p/4914245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!