下面是测试案例,只测试过itouch,iphone
http://06wjin.sinaapp.com/billd/
http://06wjin.sinaapp.com/billd/test.html
重力感应主要用到两种事件:
1 orientationchange
这个事件在屏幕发生翻转时触发
window.orientation可得到设备的方向,一共有三个值0:竖直, 90:右旋, -90:左旋
2
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; } }