IOS UIDynamicAnimator masksToBounds does not make collision work as bounds

520 views Asked by At

I work in Xcode 7, application for IOS 9. The goal is to get round objects behave like a balls using UIDynamicAnimator, UIGravityBehavior and UICollisionBehavior. Everything works fine except that UIViews (representing balls) looks rounded but behave during collision like rectangles. Code that build and adds 'balls' is:

-(void) addBall{
    CGRect frame;
    frame.origin=CGPointZero;
    frame.size = [self randomsize];
    int x = (arc4random()%(int)self.inputView.bounds.size.width);
    frame.origin.x = x;
    UIView *bullet = [[UIView alloc] initWithFrame:frame];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10,40,20)];
    label.text = @"label";
    bullet.backgroundColor = [self randomColor];
    bullet.layer.cornerRadius = bullet.frame.size.width/2;
    bullet.layer.borderWidth = 2.0;
    bullet.layer.borderColor = [UIColor blackColor].CGColor;
    bullet.layer.masksToBounds=YES;

    [bullet addSubview:label];
    [self.inputView addSubview:bullet];
    [self.gravity addItem:bullet];
    [self.collider addItem:bullet];
}

Which property needs to be set to get those objects behave like round shapes?

Below is the screen of the app showing how gravity and collision affected shapes lay on the ground/border. I draw rectangular borders on the screenshot to show real border that are invisible but prevents balls from behaving as rounded objects.

application screenshot1

2

There are 2 answers

0
beyowulf On BEST ANSWER

You should subclass UIView and overload collisionBoundsType. Something like:

-(UIDynamicItemCollisionBoundsType) collisionBoundsType
{
    return UIDynamicItemCollisionBoundsTypeEllipse;
}
0
Fonix On

In Swift you can just make an extension instead of creating a subclass which may be easier than beyowulfs answer, can just drop it at the bottom of your class if you just need it once off

extension UIView {
    func collisionBoundsType () -> (UIDynamicItemCollisionBoundsType) {
        return UIDynamicItemCollisionBoundsType.ellipse
    }
}