所以我正在开发一个允许用户解决拼图游戏的Ipad应用程序。我已经计算出每件作品的平移动作,但是将它们放到我想要的位置却没有正常工作。当它在一个很小的范围内,然后发出咔哒声时,我试图让它成为它的最终目的地。
以下是单个拼图的一些代码。按下我的新游戏按钮后,图像视图将被设置为相应的图片,并随机放置在画布上。
@IBAction func NewGameTapped(sender: UIButton){
let bounds = UIScreen.mainScreen().bounds
let height = bounds.size.height
let width = bounds.size.width
image1.image = UIImage(named:"puzzleImage1.png")
image1.center.x = CGFloat(100 + arc4random_uniform(UInt32(width)-300))
image1.center.y = CGFloat(100 + arc4random_uniform(UInt32(height)-300))
//Create Panning (Dragging) Gesture Recognizer for Image View 1
let panRecognizer1 = UIPanGestureRecognizer(target: self, action: "handlePanning1:")
// Add Panning (Dragging) Gesture Recognizer to Image View 1
image1.addGestureRecognizer(panRecognizer1)
}
这是我遇到一些问题的地方。
func handlePanning1(recognizer: UIPanGestureRecognizer) {
let center = dict1_image_coordinates["puzzleImage1"] as![Int]
let newTranslation: CGPoint = recognizer.translationInView(image1)
recognizer.view?.transform = CGAffineTransformMakeTranslation(lastTranslation1.x + newTranslation.x, lastTranslation1.y + newTranslation.y)
if recognizer.state == UIGestureRecognizerState.Ended {
lastTranslation1.x += newTranslation.x
lastTranslation1.y += newTranslation.y
}
checkPosition(image1, center: center)
}
func checkPosition(image: UIImageView, center: [Int]){
let distance: Double = sqrt(pow((Double(image.center.x) - Double(center[0])),2) + pow((Double(image.center.y) - Double(center[1])),2))
//if the distance is within range, set image to new location.
if distance <= 20{
image.center.x = CGFloat(center[0])
image.center.y = CGFloat(center[1])
AudioServicesPlaySystemSound(clickSoundID)
}
无论出于何种原因,当棋子在可接受的捕捉距离内开始游戏时,拼图只想抓住它的位置。我已经尝试在程序的各个不同部分检查对象位置,但到目前为止还没有任何工作。非常感谢任何帮助或其他提示。
答案 0 :(得分:0)
问题很可能是由此行造成的
image1.addGestureRecognizer(panRecognizer1)
通常人们在parentView上添加gestureRecognizer,或者在视图控制器的rootView上添加,而不是image1本身。好处是parentView永远不会移动,因为image1经常被转换,这可能会或可能不会影响recognizer.translationInView(x)
方法的返回值。
改为:
self.view.addGestureRecognizer(panRecognizer1)
并在handlePanning1
函数中更改为此行:
image1.transform = CGAffineTransformMakeTranslation(lastTranslation1.x + newTranslation.x, lastTranslation1.y + newTranslation.y)