import UIKit
import SpriteKit
class GameScene: SKScene {
var snake: Snake?
override func didMove(to view: SKView) {
backgroundColor = SKColor.black
snake = Snake(scene: self)
}
override func update(_ currentTime: TimeInterval) {
snake?.move()
}
override func touchesDirection(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
snake?.setDirection(location: location)
}
}
}
class Snake {
var body: [SKSpriteNode] = []
var direction: CGPoint = CGPoint(x: 1, y: 0)
var scene: GameScene
init(scene: GameScene) {
self.scene = scene
let head = SKSpriteNode(color: SKColor.green, size: CGSize(width: 20, height: 20))
head.position = CGPoint(x: scene.size.width/2, y: scene.size.height/2)
scene.addChild(head)
body.append(head)
}
func move() {
var lastPosition = body[0].position
for i in 0..<body.count {
let currentPart = body[i]
let prevPart = (i == 0) ? currentPart : body[i – 1]
currentPart.position = prevPart.position
}
body[0].position.x += direction.x * 20
body[0].position.y += direction.y * 20
}
func setDirection(location: CGPoint) {
let head = body[0]
let angle = atan2(location.y – head.position.y, location.x – head.position.x)
direction = CGPoint(x: cos(angle), y: sin(angle))
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
let scene = GameScene(size: view.bounds.size)
scene.scaleMode = .aspectFill
view.presentScene(scene)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var prefersStatusBarHidden: Bool {
return true
}
}
extension GameViewController {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let view = self.view as? SKView {
if let scene = view.scene as? GameScene {
scene.touchesDirection(touches, with: event)
}
}
}
}