1.按照我们加速计学习初步的理论,我们只要在代理事件
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
中实现相应的方法
CGPoint pos = ball.position;
pos.x += acceleration.x *10;
pos.y += acceleration.y *10;
ball.position = pos;
就可以出发对ball的响应。可是试验之后,发现效果很不明显,如何才能更流畅的对加速计事件进行相应呢?
2这就需要我们的高低滤波算法。
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
//此处将添加更多代码
#define kFilteringFactor 0.1
#define kRestAccelY -0.6
#define kMaxDiffX 0.2
#define kMaxDiffY 0.2
#define kMaxPointsPerSecX (winSize.width*0.5)
#define kMaxPointsPerSecY (winSize.height*0.5)
UIAccelerationValue rollingX,rollingY;
// UIAccelerationValue rollingZ;
//计算出我们的低通滤波算法得到重力影响的xyz值
rollingX = (acceleration.x * kFilteringFactor) +(rollingX *(1.0 - kFilteringFactor));
rollingY = (acceleration.y * kFilteringFactor) +(rollingY *(1.0 - kFilteringFactor));
// rollingZ = (acceleration.z * kFilteringFactor) +(rollingZ *(1.0 - kFilteringFactor));
//获得经去除重力影响之后的xyz的加速计影响值
float accelX = acceleration.x - rollingX;
float accelY = acceleration.y - rollingY;
// float accelZ = acceleration.z - rollingZ;
CGSize winSize = [CCDirector sharedDirector].winSize;
float accelFractionX = accelX / kMaxDiffX;
float pointsPerSecX = kMaxPointsPerSecX * accelFractionX;
float accelDiffY = accelY - kRestAccelY;
float accelFractionY = accelDiffY /kMaxDiffY;
float pointsPerSecY = kMaxPointsPerSecY * accelFractionY;
velocityX = pointsPerSecX;
velocityY = pointsPerSecY;
//经过上述的处理,我们便可以对加速计事件进行流畅的相应。
}
3.对我们的加速计事件 进行 update的频率检测
以便于及时响应我们的加速计事件的改变
-(void)update:(ccTime)delta{
CGSize winSize = [CCDirector sharedDirector].winSize;
//设置小球在横向和纵向的移动边界
float maxY = winSize.height -ball.contentSize.height/2;
float minY = ball.contentSize.height/2;
float maxX = winSize.width - ball.contentSize.width/2;
float minX = ball.contentSize.width/2;
//根据加速度数据计算出小球的最终y坐标,注意使用了一个简单的算法来确保小球不会超出边界
float newY = ball.position.y + (velocityY *delta);
newY = MIN(MAX(newY, minY),maxY);
//根据加速度数据计算出小球的最终x坐标,注意使用了一个简单的算法来确保小球不会超出边界
float newX = ball.position.x + (velocityX *delta);
newX = MIN(MAX(newX, minX),maxX);
//更新小球的位置
ball.position = ccp(newX,newY);
}