我正在尝试在iOS
我正在开发的应用程序中创建一些动画。我有一个盒子会掉下来,直到它撞到一个酒吧。我还在框中添加了一个bounce
对栏的影响。我现在要添加的是杆上的一种行为,因此当盒子碰到杆时,反应是轻微的弹簧。我尝试添加一个UIAttachmentBehavior
但无法弄清楚如何正确实现它。我已经看过WWDC
视频和其他视频,但我无法让它在这个设置中工作。如果你能在这个例子中告诉我如何实现它,那就太好了。
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_mainView = [[UIView alloc] initWithFrame:[[self view] bounds]];
[_mainView setBackgroundColor:[UIColor clearColor]];
[[self view] addSubview: _mainView];
_objectView =
[[UIView alloc] initWithFrame:CGRectMake(_mainView.bounds.size.width/2-40, 40,
80, 80)];
[_objectView setBackgroundColor:[UIColor redColor]];
[_mainView addSubview: _objectView];
_barView =
[[UIView alloc] initWithFrame:CGRectMake(_mainView.bounds.size.width/2-50,
(_mainView.bounds.size.height/5) * 4,
100, 3)];
[_barView setBackgroundColor:[UIColor blackColor]];
[_mainView addSubview: _barView];
//----------------------------------
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:_mainView];
BounceCustomBehavior *bouncyBehavior =
[[BounceCustomBehavior alloc]
initWithItems:@[_objectView]
objects:[NSArray arrayWithObjects:_barView, nil]];
[_animator addBehavior:bouncyBehavior];
//-----------------------------------
}
#import "BounceCustomBehavior.h"
@implementation BounceCustomBehavior
-(instancetype)initWithItems:(NSArray *)items objects:(NSArray *)collisionObjs {
if (!(self = [super init])) return nil;
UIGravityBehavior* gravityBehavior = [[UIGravityBehavior alloc] initWithItems:items];
[self addChildBehavior:gravityBehavior];
UICollisionBehavior* collisionBehavior = [[UICollisionBehavior alloc] initWithItems:items];
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
for (UIView * view in collisionObjs) {
CGPoint rightEdge = CGPointMake(view.frame.origin.x +
view.frame.size.width, view.frame.origin.y);
[collisionBehavior addBoundaryWithIdentifier:@""
fromPoint:view.frame.origin
toPoint:rightEdge];
}
[self addChildBehavior:collisionBehavior];
UIDynamicItemBehavior *elasticityBehavior = [[UIDynamicItemBehavior alloc] initWithItems:items];
elasticityBehavior.elasticity = 0.3f;
[self addChildBehavior:elasticityBehavior];
return self;
}
@end