How can I animate a UICollisionBehavior to a moving UIView element on iOS?

78 views Asked by At

I am working on a game, in which you have to hit a target with a flickable ball.

  • The target (UIView) is animated as a CABasicAnimation.
  • The ball (UIImageView) is assigned an animator, which itself is assigned a UICollisionBehavior, containing the target and the football.

So now I hit the target with the ball, but nothing happens. If I hit the origin point of the target however, a collision takes place: The ball bounces back from an invisible object, and the target on the other side of the screen moves, as if hit by the ball.

So apparently just the target is animated, but not the collision attribute. How can I fix this?

UICollisionBehavior - Code

self.animator = UIDynamicAnimator(referenceView: football.superview!)
collision = UICollisionBehavior(items: [football,target])
collision.collisionDelegate = self
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)

CABasicAnimation - Code

    func coreAnimateGoalRight(){
        let animation = CABasicAnimation(keyPath: "position.x")
        animation.fromValue = target.center.x
        animation.toValue = screenSize.width - target.frame.size.width/2
        animation.duration = 5
        animation.fillMode = .forwards
        animation.autoreverses = true
        animation.isRemovedOnCompletion = false
        animation.beginTime = CACurrentMediaTime()
        
        target.layer.add(animation, forKey: nil)
        
    }
0

There are 0 answers