2012-10-06 43 views
4

我想使用加速計移動一個圓圈內的圖像。我有一個問題,當圖像碰到圓的邊緣時,它會移動圓的另一邊。我的代碼如下:iOS使用加速度計移動一個圓圈內的物體

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { 
//NSLog(@"x : %g", acceleration.x); 
//NSLog(@"y : %g", acceleration.y); 
//NSLog(@"z : %g", acceleration.z); 

delta.x = acceleration.x * 10; 
delta.y = acceleration.y * 10; 

joypadCap.center = CGPointMake(joypadCap.center.x + delta.x, joypadCap.center.y - delta.y); 

distance = sqrtf(((joypadCap.center.x - 160) * (joypadCap.center.x - 160)) + 
       ((joypadCap.center.y -206) * (joypadCap.center.y - 206))); 
//NSLog(@"Distance : %f", distance); 


touchAngle = atan2(joypadCap.center.y, joypadCap.center.x); 
NSLog(@"Angle : %f", touchAngle); 


if (distance > 50) { 
    joypadCap.center = CGPointMake(160 - cosf(touchAngle) * 50, 206 - sinf(touchAngle) * 50); 
} 

回答

4

我在嘗試使用CMDeviceMotion實現循環水平時遇到同樣的問題。我發現這是一個問題,座標傳遞給atan2(y,x)。此功能需要笛卡爾座標,並且(0,0)位於視圖的中心。但是,屏幕座標在左上角有(0,0)。我創建了方法來轉換兩個座標系之間的一個點,現在它運行良好。

我提出了一個樣本項目here GitHub上,但這裏的最重要的部分:

float distance = sqrtf(((point.x - halfOfWidth) * (point.x - halfOfWidth)) + 
         ((point.y - halfOfWidth) * (point.y - halfOfWidth))); 

if (distance > maxDistance) 
{ 
    // Convert point from screen coordinate system to cartesian coordinate system, 
    // with (0,0) located in the centre of the view 
    CGPoint pointInCartesianCoordSystem = [self convertScreenPointToCartesianCoordSystem:point 
                       inFrame:self.view.frame]; 

    // Calculate angle of point in radians from centre of the view 
    CGFloat angle = atan2(pointInCartesianCoordSystem.y, pointInCartesianCoordSystem.x); 

    // Get new point on the edge of the circle 
    point = CGPointMake(cos(angle) * maxDistance, sinf(angle) * maxDistance); 

    // Convert back to screen coordinate system 
    point = [self convertCartesianPointToScreenCoordSystem:point inFrame:self.view.frame]; 
} 

和:

- (CGPoint)convertScreenPointToCartesianCoordSystem:(CGPoint)point 
              inFrame:(CGRect)frame 
{ 
    float x = point.x - (frame.size.width/2.0f); 
    float y = (point.y - (frame.size.height/2.0f)) * -1.0f; 

    return CGPointMake(x, y); 
} 

- (CGPoint)convertCartesianPointToScreenCoordSystem:(CGPoint)point 
              inFrame:(CGRect)frame 
{ 
    float x = point.x + (frame.size.width/2.0f); 
    float y = (point.y * -1.0f) + (frame.size.height/2.0f); 

    return CGPointMake(x, y); 
}