通过倾斜设备移动节点

时间:2014-02-17 15:07:10

标签: ios iphone objective-c ios7

我想通过左右倾斜我的设备来移动球体。我现在的代码正在工作,除了我必须上下倾斜设备 - 当我声明data.acceleration.y - > Y轴?

这是我的代码:

 motionManager = [[CMMotionManager alloc] init];
if ([motionManager isAccelerometerAvailable] == YES) {
    [motionManager startAccelerometerUpdatesToQueue:[[NSOperationQueue alloc] init]
                                        withHandler:^(CMAccelerometerData *data, NSError *error)
     {
         float destX, destY;
         float currentX = sphereNode.position.x;
         float currentY = sphereNode.position.y;
         BOOL shouldMove = NO;

         if(data.acceleration.y < -0.25) { // tilting the device to the right
             destX = currentX + (data.acceleration.y * kPlayerSpeed);
             destY = currentY;
             shouldMove = YES;
         } else if (data.acceleration.y > 0.25) { // tilting the device to the left
             destX = currentX + (data.acceleration.y * kPlayerSpeed);
             destY = currentY;
             shouldMove = YES;
         }
         if(shouldMove) {
             SKAction *action = [SKAction moveTo:CGPointMake(destX, destY) duration:1];
             [sphereNode runAction:action];
         }
     }];
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

Y轴确实与设备的顶部和底部对齐。您很可能正在寻找CMAccelerometerData数据对象的x轴。

Event handling guide for iOS : Motion Events文档中对此进行了解释。

也许查看一些教程(例如iOS Programming Recipe 19: Using Core Motion to Access Gyro and Accelerometer)也可以帮助你。