Is it possible to simulate gravity to an object / UIView in UIDynamicKit?

179 views Asked by At

Without using SpriteKit, is it possible to simulate gravity for UIView object? What I'm trying to achieve is a center UIView with other object floating around it. Almost like planets around a Sun. And also have it attract and repulse from the center object.

I know you can add horizontal and vertical gravity to the superview.

Thanks!

2

There are 2 answers

0
Tuan Anh Vu On

The solution is to use UIAttachmentBehavior.

let attachment = UIAttachmentBehavior(item: node, attachedTo: self.ownerNode)

            self.animator.addBehavior(attachment)

The above code will have the node objects attached to the self.ownerNode. I also added UISnapBehavior to self.ownerNode so that when dragged away from the center, the self.ownerNode will always snap back to the center and all have all other nodes follow it.

let snapCenter = UISnapBehavior(item: self.ownerNode, snapTo: self.view.center)
            self.animator.addBehavior(snapCenter)
0
Confused On

Another approach: Use a field.

UIKit Dynamics brought fields to the table sometime around iOS 9, I think.

Fields provide same, similar or unique vectors of "force" for all the positions within their... field of influence. Hence the name.

You can switch a field, so it's pushing at one moment, pulling at another, or even combine them, layer them and align them around a screen in regions of influence.

A single field can act like planetary gravitational force in the middle of your screen, making satellites move around it, fall into it, or be repelled away.

Fields are a very powerful feature of UIKit Dynamics, both in terms of creativity and influence. They're also remarkably efficient because they only act on those things you stipulate to be influenced by them. So whilst their field size might be large, and their functions determining positional influence complex, they're still very efficient.

You can read/watch/listen to more about them here:

https://developer.apple.com/videos/play/wwdc2015/229/