3
我正在使用cocos2d在iPhone遊戲上工作。我正在嘗試使用加速度計在縱向模式下移動精靈來左右移動。出於某種原因,我使用的代碼默認爲向右移動,除非手機以45度角傾斜,即返回值都爲正值(表示它應該向右移動),直到它以45度角傾斜,無論是向左還是向右。死亡中心返回到600左右,然後減少進一步向左或向右傾斜手機,直至它達到45度角(在此點擊0並開始變爲負值)。以下是我正在使用的代碼。任何幫助將非常感謝。使用iPhone加速度計沿x軸移動精靈
- (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);
}
查看清楚的解決方案:http://gamedev.stackexchange.com/questions/33412/accelerometer-to-move-player-left-and-right/33427#33427 – Guru 2014-03-28 12:43:42