import SpriteKit
class GameScene: SKScene {
var cam: SKCameraNode?
var player: SKSpriteNode?
override func didMove(to view: SKView) {
super.didMove(to: view)
cam = SKCameraNode()
self.camera = cam
self.addChild(cam!)
player = self.childNode(withName: "player") as? SKSpriteNode
}
func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch:UITouch = touches.anyObject() as! UITouch
let touchLocation = touch.location(in: self)
if touchLocation.x < self.frame.size.width / 2 {
let moveRight = SKAction.moveBy(x: 300, y: 0, duration: 1)
player?.run(moveRight)
} else {
let moveLeft = SKAction.moveBy(x: -300, y: 0, duration: 1)
player?.run(moveLeft)
}
}
override func update(_ currentTime: TimeInterval) {
super.update(currentTime)
if let camera = cam, let pl = player {
camera.position = pl.position
}
}
}
That is my whole game scene and the sprites I have dragged and dropped onto the screen using the sk scene. I have added a camera to the scene if that affects anything. Thanks for any help.
2
Answers
I figured it out with the help of JohnL. By adding if touchLocation.x < (player?.position.x)! instead of if touchLocation.x < self.frame.size.width / 2
You need to override the touches began function. It also helps to put in a print statement to show that touches are being received.