- (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);}解决方法 尝试使用CMDeviceMotion实现循环水平仪时,我遇到了同样的问题.我发现传递给atan2(y,x)的坐标是一个问题.此功能需要笛卡尔坐标,视图中心有(0,0).但是,屏幕坐标左上角有(0,0).我创建了在两个坐标系之间转换点的方法,现在它运行良好.
我在github上设置了一个示例项目here,但这是最重要的部分:
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 @R_419_4741@ 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);}总结
以上是内存溢出为你收集整理的iOS使用加速度计在圆圈内移动对象全部内容,希望文章能够帮你解决iOS使用加速度计在圆圈内移动对象所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)