我正在使用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);
}
答案 0 :(得分:1)
基本上,您的加速度计应该做的是更新加速度(使用像您一样的过滤因子)。
但是在它旁边你应该保持速度和位置,并在你的预定步骤(浮动dt)函数中进行调整:
速度+ =加速度* dt 位置+ =速度* dt
为x和y执行此操作