球在一个不可见的盒子内反弹/移动ios/xcode

球在一个不可见的盒子内反弹/移动ios/xcode,ios,objective-c,ipad,Ios,Objective C,Ipad,我希望当用户摇动设备时,球在屏幕上的对象内部发出嘎嘎声。我假设我需要设置一个不可见的盒子,让它与之碰撞。不管它是随机移动还是遵循预定义的路径,以最简单的为准 我想我理解了代码中的“在摇晃时激活”部分,只是球/物体的移动我不确定这应该会起作用: //You need an @property (nonatomic, strong) UIDynamicAnimator *animator; in your .h self.animator = [[UIDynamicAnimator alloc] i

我希望当用户摇动设备时,球在屏幕上的对象内部发出嘎嘎声。我假设我需要设置一个不可见的盒子,让它与之碰撞。不管它是随机移动还是遵循预定义的路径,以最简单的为准

我想我理解了代码中的“在摇晃时激活”部分,只是球/物体的移动我不确定

这应该会起作用:

//You need an @property (nonatomic, strong) UIDynamicAnimator *animator; in your .h
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.viewToBounceAroundIn];

UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.viewThatBouncesAround]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collision];

UIPushBehavior *push = [[UIPushBehavior alloc] initWithItems:@[self.viewThatBouncesAround] mode:UIPushBehaviorModeInstantaneous];
push.magnitude = 1; //Play with this, it's how much force is applied to your object
push.angle = 0; //play with this too
[self.animator addBehavior:push];
我是从一个编译器那里输入的,请告诉我它是否有效。这个想法是,你用一个物理引擎,用一个来让物体在盒子里弹来弹去,用一个来施加初始力

如果项目的速度对您来说太快,或者从墙上反弹时损失太多能量,您可以调整其属性:

UIDynamicItemBehavior *behavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.itemThatBouncesAround]];
behavior.friction = 0; //no friction. play with this.
behavior.elasticity = 1;; //completely elastic, play with this.
[self.animator addBehavior:behavior];
这应该起作用:

//You need an @property (nonatomic, strong) UIDynamicAnimator *animator; in your .h
self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.viewToBounceAroundIn];

UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.viewThatBouncesAround]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:collision];

UIPushBehavior *push = [[UIPushBehavior alloc] initWithItems:@[self.viewThatBouncesAround] mode:UIPushBehaviorModeInstantaneous];
push.magnitude = 1; //Play with this, it's how much force is applied to your object
push.angle = 0; //play with this too
[self.animator addBehavior:push];
我是从一个编译器那里输入的,请告诉我它是否有效。这个想法是,你用一个物理引擎,用一个来让物体在盒子里弹来弹去,用一个来施加初始力

如果项目的速度对您来说太快,或者从墙上反弹时损失太多能量,您可以调整其属性:

UIDynamicItemBehavior *behavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.itemThatBouncesAround]];
behavior.friction = 0; //no friction. play with this.
behavior.elasticity = 1;; //completely elastic, play with this.
[self.animator addBehavior:behavior];