So I am new to Swift and I am trying to figure out how to split the screen basically in half and make it so that if the right side of the screen is tapped then the object will move over to the right and if the left side of the screen is tapped then the object will move over to the left. I have tried to play around with the gestures but I haven't gotten very far. How can I fix this? It gives me an error at locationinNode
I am using storyboard to add the moving object.
This is what I have:
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
}
}
}
What's the touch
in the touchesBegan
? I think you should use the touches.first as! UITouch
like so:
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
}
}