Cocos2D和iPhone的加速度计

时间:2012-04-29 23:09:35

标签: iphone objective-c cocos2d-iphone accelerometer

下午好!

今天我开始开发游戏,但我遇到了麻烦。所以,首先我想说我没有开发游戏的经验......

所以,我在图层中有一个CCSprite,我希望在带有边距(顶部,底部,左边和右边)的场景之间移动它。

最小X应为-0.8(使用加速度计在X轴上)和最大值8.最小值Y应为-1(在Y轴上)或Z轴为0,最大值为0(在Y轴上) -axis)或-1(在Z轴上)。

好的,知道了这一点,我尝试使用最小和最大空间和加速度计值之间的范围来做这件事,但我没有让它垂直工作(iPhone上的Y轴)。然后我在网上得到了一个完成的代码,但是当我想将对象移回去时(对象只有),这不起作用。

有人知道如何解决这个问题吗?

我的实际代码:

- (void)updatePosition:(ccTime)dt {
    CGSize winSize = [[CCDirector sharedDirector] winSize];

    float maxY = winSize.height - car.contentSize.height/2 - 20;
    float minY = car.contentSize.height/2 + 20;
    float newY = car.position.y + (carPointsPerSecY * dt);
    newY = MIN(MAX(newY, minY), maxY);

    float maxX = winSize.width - car.contentSize.width/2 - 40;
    float minX = car.contentSize.width/2 + 40;
    float newX = car.position.x + (carPointsPerSecX * dt);
    newX = MIN(MAX(newX, minX), maxX);

    car.position = ccp(newX, newY);
}    

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    float speedY = acceleration.y * 500;
    if(carPointsPerSecY < speedY) {
        carPointsPerSecY = MIN(carPointsPerSecY + 10, speedY);
    } else {
        carPointsPerSecY = MAX(carPointsPerSecY - 2, speedY);
    }

    float speedX = acceleration.x * 200;
    if(carPointsPerSecX < speedX) {
        carPointsPerSecX = MIN(carPointsPerSecX + 10, speedX);
    } else {
        carPointsPerSecX = MAX(carPointsPerSecX - 10, speedX);
    }

    NSLog(@"Acceleration: X (%f) - Y (%f) - Z (%f)", acceleration.x, acceleration.y, acceleration.z);
}

1 个答案:

答案 0 :(得分:0)

我不确定我完全理解你想要什么,但我希望这可以帮助你实现最终目标:

-(void)updatePosition:(ccTime)dt {
    CGSize size = [[CCDirector sharedDirector] winSize];

    int margin = 20;
    float speed = 15;

    float maxX = size.width - car.contentSize.width / 2 - margin;
    float minX = car.contentSize.width / 2 + margin;
    float maxY = size.height - car.contentSize.height / 2 - margin;
    float minY = car.contentSize.height / 2 + margin;

    float newX = MIN(MAX(car.position.x + xAccel * speed, minX), maxX);
    float newY = MIN(MAX(car.position.y + yAccel * speed, minY), maxY);

    car.position = ccp(newX, newY);
}

//define in header: float xAccel, yAccel;
- (void)accelerometer: (UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration {
    yAccel = acceleration.x;
    xAccel = -acceleration.y;
}