Search code examples
iosswiftcollision-detection

Views doesn't collides while moving ( Swift iOS )


i am trying to use some views in my app and i am trying to animate and collide these view by hitting each other but problem is that when i use gravity these views collides but when i drag/move any view collision doesn't works. whats wrong with my code here goes my code

For moving views

  func tappedMe(gr: UIPanGestureRecognizer)
    {
        if gr.view?.tag == 1{    
                let point = gr.locationInView(self.view);
                square.center.x=point.x
                square.center.y=point.y
        }else if gr.view?.tag == 2{
            let point = gr.locationInView(self.view);
            square2.center.x=point.x
            square2.center.y=point.y
        }
    }

for Gravity

animator = UIDynamicAnimator(referenceView: view)
    gravity = UIGravityBehavior(items: [square, square2])
            let direction = CGVectorMake(0, -1)
            gravity!.gravityDirection = direction
            animator.addBehavior(gravity)

For Collision

collision = UICollisionBehavior(items: [ square, square2])
            collision.translatesReferenceBoundsIntoBoundary = true
            animator.addBehavior(collision)

thanks in advance


Solution

  • I don't think you are meant to directly manipulate views while they are attached to a UIDynamicAnimator. I think that you either need to remove all of the behaviours or add attachment behaviours at the touch point and move the attachment point during the pan gesture.

    (This is from memory, I haven't used UIDynamics very recently).