嗨,标题pre很多总结,它正在使用加速度计,但它只是继续离开屏幕,即时15我和我有很多麻烦试图让它停在边缘。这是我的视图控制器.m文件代码。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize person, delta;
- (void)viewDidLoad
{
UIAccelerometer *accel =[UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 1.0f / 60.0f;
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(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.y *50;
// delta.x = acceleration.x *8;
person.center = CGPointMake(person.center.x + delta.x,person.center.y + delta.y );
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
答案 0 :(得分:0)
更新person.center
后,您需要将其限制在视图的边框上,否则它将会脱离屏幕。
为了让您入门,这就是您可以阻止此人离开视图的左侧边缘的方式:
person.center = CGPointMake(person.center.x + delta.x,person.center.y + delta.y );
// add this
CGFloat leftOfWorld = 0.0f;
CGFloat minCenterX = leftOfWorld + (person.bounds.size.width / 2.0f);
person.center = CGPointMake(MAX(minCenterX, person.center.x), person.center.y);
当center.x
距离左边缘(宽度/ 2)时,此人位于屏幕左侧。这是我们的最低要求。然后我们在最小值和center.x
之间取较大的值,这样如果center.x
移动到此最小值以下,我们就会更改它。
您可能希望屏幕的其他边缘具有类似的逻辑。您需要使用self.view.width
和self.view.height
来计算屏幕的右下边缘。