0

下午好!

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

所以,我在图层中有一个 CCSprite,我想在场景之间移动它并留有边距(顶部、底部、左侧和右侧)。

最小 X 应为 -0.8(使用加速度计的 X 轴),最大 8。最小 Y 应为 -1(Y 轴)或 Z 轴 0,最大 0(Y 轴)或 -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);
}
4

1 回答 1

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;
}
于 2012-08-07T03:19:57.310 回答