我正在使用 cocos2d 开发 iPhone 游戏。我正在尝试使用加速度计在纵向模式下移动精灵以左右移动。由于某种原因,我使用的代码默认向右移动,除非手机倾斜 45 度角,即返回值都是正数(表示它应该向右移动),直到它倾斜 45 度角,左或右。死点返回 600 左右,然后随着您向左或向右倾斜手机的进一步降低,直到它达到 45 度角(它达到 0 并开始变为负数)。下面是我正在使用的代码。任何帮助将不胜感激。
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
#define kFilteringFactor 0.75
static UIAccelerationValue rollingX = 0, rollingY = 0, rollingZ = 0;
rollingX = (acceleration.x * kFilteringFactor) +
(rollingX * (1.0 - kFilteringFactor));
rollingY = (acceleration.y * kFilteringFactor) +
(rollingY * (1.0 - kFilteringFactor));
rollingZ = (acceleration.z * kFilteringFactor) +
(rollingZ * (1.0 - kFilteringFactor));
float accelX = rollingX;
float accelY = rollingY;
float accelZ = rollingZ;
CGSize winSize = [CCDirector sharedDirector].winSize;
#define kRestAccelX 0.6
#define kShipMaxPointsPerSec (winSize.height*0.5)
#define kMaxDiffX 0.2
float accelDiffX = kRestAccelX - ABS(accelX);
float accelFractionX = accelDiffX / kMaxDiffX;
float pointsPerSecX = kShipMaxPointsPerSec * accelFractionX;
_shipPointsPerSecX = pointsPerSecX;
NSLog(@"_shipPointsPerSecX: %f", _shipPointsPerSecX);
}
- (void)updateShipPos:(ccTime)dt {
CGSize winSize = [CCDirector sharedDirector].winSize;
float maxX = winSize.width - _ship.contentSize.width/2;
float minX = _ship.contentSize.width/2;
float newX = _ship.position.x + (_shipPointsPerSecX * dt);
newX = MIN(MAX(newX, minX), maxX);
_ship.position = ccp(newX, _ship.position.y);
// NSLog(@"newx: %f", newX);
}