UIDynamicAnimator view entering from outside of the reference bounds

浪尽此生 提交于 2019-12-12 17:15:34

问题


I would like to animate dropping an object using the UIDynamicAnimator and gravity/collision/elasticity effects. I looked at Apple's sample app DynamicsCatalog, and it is quite straight forward, except for when the object starts off from the outside the bounds of its container.

For example, this is the code taken from the sample app's APLCollisionGravityViewController.m file:

UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];

UIGravityBehavior *gravityBeahvior = [[UIGravityBehavior alloc] initWithItems:@[self.square]];
[animator addBehavior:gravityBeahvior];

UICollisionBehavior *collisionBehavior = [[UICollisionBehavior alloc] initWithItems:@[self.square]];
collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;
collisionBehavior.collisionDelegate = self;
[animator addBehavior:collisionBehavior];

It works well if the frame of self.square is initially completely within self.view. If I change it so that it has a negative frame.origin.y value, things get stranger. Specifically, if the absolute value of frame.origin.y is more than half of frame.size.height, the square appears to be "gravitating" up instead of down - it rises instead of falling.

I am looking for have the square initially completely outside of the container bounds (that is, I set frame.origin.y = -frame.size.height), how can I modify the animator/gravity/collision behaviours to accommodate that?


回答1:


The problem is that you're banging into the top boundary and causing a collision when the object tries to enter the reference view! The object is falling from outside and bouncing off the top of your reference view.

Thus your definition of the collision boundary is too simple-minded:

collisionBehavior.translatesReferenceBoundsIntoBoundary = YES;

No. You'll have to set up the collision boundaries manually. For example, start with a boundary that's just the bottom of the reference view, so that the object can enter the scene and bounce off the floor, like this:

UICollisionBehavior* coll = [UICollisionBehavior new];
coll.collisionMode = UICollisionBehaviorModeBoundaries;
coll.collisionDelegate = self;
[coll addBoundaryWithIdentifier:@"floor"
                      fromPoint:CGPointMake(0,self.view.bounds.size.height)
                        toPoint:CGPointMake(self.view.bounds.size.width,
                                            self.view.bounds.size.height)];

If you want to change to a different, enclosing set of boundaries after the first collision, fine, but first you have to let the object into the reference view. Right now you're locking it out with your collision boundaries.



来源:https://stackoverflow.com/questions/23252216/uidynamicanimator-view-entering-from-outside-of-the-reference-bounds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!