Johny D Good
Johny D Good

Reputation: 427

moving imageView from current location to tap location at a constant speed

I have a an imageView that I want to move prom current location to tapped location at a constant speed, regardless of distance.

tried the following which doesn't really work and I don't really know how to keep animation duration dynamic according to distance that imageView needs to traverse.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let position = touch.location(in: self.view)
        print(position.x)
        print(position.y)


        CATransaction.begin()
        CATransaction.setCompletionBlock { () -> Void in
            self.imageView.layer.position = (self.imageView.layer.presentation()?.position)!
        }
        var animation = CABasicAnimation(keyPath: "position")
        animation.duration = 2


        var currentPosition : CGPoint = imageView.layer.presentation()!.position
        animation.fromValue = NSValue(currentPosition)
        animation.toValue = NSValue(CGPoint: position.x, (position.y))
        animation.isRemovedOnCompletion = false
        animation.fillMode = kCAFillModeForwards
        imageView.layer.add(animation, forKey: "transform")
        CATransaction.commit()




    }
}

Upvotes: 1

Views: 474

Answers (2)

Reinier Melian
Reinier Melian

Reputation: 20804

Try with this

calculating the distance

func distance(_ a: CGPoint, _ b: CGPoint) -> CGFloat {
        let xDist = a.x - b.x
        let yDist = a.y - b.y
        return CGFloat(sqrt((xDist * xDist) + (yDist * yDist)))
    }

and then using a arbitrary velocity, and calculating the time

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let position = touch.location(in: self.view)
            print(position.x)
            print(position.y)

            let distance = Double(self.distance(self.imageView.center, position))
            let velocity = 100.0 //pixels by seconds


            let time = distance / velocity

            UIView.animate(withDuration: time, animations: {
                self.imageView.center = position
            })


        }
    }

Upvotes: 3

Pratik Lad
Pratik Lad

Reputation: 464

You can add UITapGestureRecognizer of imageView parent view and create tap gesture action

@IBAction func tapGesture(_ sender: UITapGestureRecognizer) {
    print("tap working")
    if sender.state == UIGestureRecognizerState.recognized
    {
        let location = sender.location(in: sender.view)
        print(location)
        UIView.animate(withDuration: 0.5, animations: {
            self.imageView.center = location
        })

    }
}

Upvotes: 0

Related Questions