为什么我的精灵不能用加速度计移动?

时间:2011-12-04 21:45:12

标签: iphone objective-c cocos2d-iphone

我一直试图解决这个问题几个小时,没有运气。我试图使我的CCSprite子类(thePlayer)沿着Y轴在屏幕上相对于设备的倾斜移动。我以前做过,一切都应该有效,但由于某种原因,它不是。这是代码:

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    CGSize WinSize = [[CCDirector sharedDirector] winSize];
#define kFilteringFactor 0.1
#define kRestAccelX -0.6
#define kShipMaxPointsPerSec (WinSize.height*0.5)        
#define kMaxDiffX 0.2
    UIAccelerationValue rollingX, rollingY, rollingZ;
    rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));
    float accelX = acceleration.x - rollingX;
    float accelDiff = accelX - kRestAccelX;
    float accelFraction = accelDiff / kMaxDiffX;
    float pointsPerSec = kShipMaxPointsPerSec * accelFraction;
    _shipPointsPerSecY = pointsPerSec;
    //CCLOG(@"PointsPerSec: %f", _shipPointsPerSecY);
    CGPoint pos = thePlayer.position;
    pos.y += _shipPointsPerSecY;
    CCLOG(@"Pos.y: %f", pos.y);
    thePlayer.position = pos;
}

- (void)update:(ccTime)dt
{
    CGSize WinSize = [[CCDirector sharedDirector] winSize];
    float maxY = WinSize.height - thePlayer.contentSize.height / 2;
    float minY = thePlayer.contentSize.height/2;
    float derp = _shipPointsPerSecY;
    //CCLOG(@"Derp: %f", derp);
    float newY = thePlayer.position.y + (_shipPointsPerSecY * dt);
    //CCLOG(@"NewY: %f", newY);
    newY = MIN(MAX(newY, minY), maxY);
    thePlayer.position = ccp(thePlayer.position.x, newY);
    //CCLOG(@"Player position Y: %f", thePlayer.position.y);
}

这可能是我遇到的第二个最烦人的问题,所以感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

您的pos.y似乎最终会根据acceleration.x进行调整;只是想确保你不会混淆你的X和Y值。

另请注意,加速度计的X和Y通常与屏幕的相同对齐有关,无论其方向如何。因此在横向上,acceleration.x实际上是你的Y值,反之亦然。如果这也适用于此。