2015-06-08 49 views
1

所以我對Swift很陌生,我試圖弄清楚如何將屏幕基本上分成兩半,並且使得如果屏幕的右側被點擊,那麼對象將移動到右側,如果左側輕擊屏幕的一側,然後對象將移動到左側。我嘗試過打手勢,但是我還沒有走得很遠。我怎樣才能解決這個問題?它給我錯誤在locationinNode將遊戲畫面分成左右兩部分?

我使用故事板來添加移動的對象。

這是我有:

import UIKit 
class ViewController: UIViewController { 

@IBOutlet var Lane: [UIImageView]! 
@IBOutlet weak var Player: UIImageView! 
@IBOutlet weak var Platform: UIImageView! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func MoveLeft(){ 
    UIView.animateWithDuration(0.2, delay: 0, options:UIViewAnimationOptions.CurveLinear, animations: { 
     self.Player.center = CGPoint(x: self.Player.center.x - 125, y: self.Player.center.y) 
     }, completion: nil) 
} 

func MoveRight(){ 
    UIView.animateWithDuration(0.2, delay: 0, options:UIViewAnimationOptions.CurveLinear, animations: { 
     self.Player.center = CGPoint(x: self.Player.center.x + 125, y: self.Player.center.y) 
     }, completion: nil) 
} 

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
let location = touch.locationInNode(self) 
if location.x < self.size.width/2 { 
// left code 
MoveLeft() 
} 
else { 
    // right code 
} 

} 

} 

回答

4

是什麼在touchesBegantouch?我想你應該使用touches.first as! UITouch像這樣:

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { 
    let location = (touches.first as! UITouch).locationInView(self.view) 
    if location.x < self.view.bounds.size.width/2 { 
     // left code 
     MoveLeft() 
    } else { 
     // right code 
    } 
} 
+0

好了,所以我代替它,但它給我的錯誤:「不能援引‘locationInView’類型的參數列表‘(視圖控制器)’ –

+0

而不是使用'self' with'self.view' – Bannings

+0

你是最棒的!非常感謝你@Bannings如果我可以再問你一個問題,如果我想限制對象不在屏幕外面怎麼辦? –