0

嗨,标题预先总结了它,它正在使用加速度计,但它一直在屏幕外,我 15 岁,我在试图让它停在边缘时遇到了很多麻烦。这是我的视图 controller.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
4

1 回答 1

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当距离左边缘 (width / 2)时,人在屏幕的左侧。这是我们的最低要求。然后我们在最小值之间取较大的值,center.x所以如果center.x低于这个最小值,我们就改变它。

对于屏幕的其他边缘,您可能需要类似的逻辑。您需要使用self.view.width和计算屏幕的右边缘和下边缘self.view.height

于 2013-04-12T09:47:44.377 回答