首页 新随笔 联系 订阅 管理 个人网站

移动端html5重力感应

下面是测试案例,只测试过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)
 
坐标系见下图
 移动端html5重力感应 - FIR - 显微镜
 
下面是示例游戏用到重力感应的代码:
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;
    }
}
posted @ 2015-10-27 14:56  __不粘锅  阅读(1850)  评论(0编辑  收藏  举报