i am writing an App where i use UIKit Dynamics to simulate the interactions of different circles with one another.
I create my circles with the following code:
self = [super initWithFrame:CGRectMake(location.x - radius/2.0, location.y - radius/2, radius, radius)];
if (self) {
[self.layer setCornerRadius: radius /2.0f];
self.clipsToBounds = YES;
self.layer.masksToBounds = YES;
self.backgroundColor = color;
self.userInteractionEnabled = NO;
}
return self;
where location represents the desired location of the circle, and radius its radius.
I then add these circles to different UIBehaviours, by doing:
[_collision addItem:circle];
[_gravity addItem:circle];
[_itemBehaviour addItem:circle];
The itemBaviour is defined as follows:
_itemBehaviour = [[UIDynamicItemBehavior alloc] initWithItems:@[square]];
_itemBehaviour.elasticity = 1;
_itemBehaviour.friction = 0;
_itemBehaviour.resistance = 0;
_itemBehaviour.angularResistance = 0;
_itemBehaviour.allowsRotation = NO;
The problem i am having, is that my circles are behaving as squares. When hit in certain ways they gain angular momentum and lose speed. If they collide again, sometimes the angular momentum is again reverted to speed. This looks normal for squares, but when the view is round, like in my case, this behaviour looks weird and unnatural.
Turning on some debug options, i made this screenshot:
As you can see, the circle is appearently a square.
So my question is, how can i create an UIVIew that is truly a circle and will behave as such in UIKit Dynamics?
I know this question predated iOS 9, but for the benefit of future readers, you can now define a view with
collisionBoundsType
ofUIDynamicItemCollisionBoundsTypePath
and a circularcollisionBoundingPath
.So, while you cannot "create an
UIView
that is truly a circle", you can define a path that defines both the shape that is rendered inside the view as well as the collision boundaries for the animator, yielding an effect of a round view (even though the view, itself, is obviously still rectangular, as all views are):Then, when you do your collision, it will honor the
collisionBoundingPath
values:That yields:
By the way, it should be noted that the documentation outlines a few limitations to the path:
But a simple circle path easily meets those criteria.
Or, for Swift users:
Ok, well first off.
The debug options you enabled show areas of transparent cells. The view that is the circle is actually a square with rounded edges.
All views are rectangular. The way they appear circular is by making the corners transparent (hence corner radius).
Second, what is it you're trying to do with UIKit Dynamics? What is on the screen looks like you're trying to create a game of some sort.
Dynamics is meant to be used for more natural and real looking animation of UI. It isn't meant to be a full-on physics engine.
If you want something like that then you're best using Sprite Kit.