实现简单的用户交互,控制节点操作
import SpriteKit
import GameplayKit
class GameTouch: SKScene {
var backgroundNode : SKSpriteNode!
var zombieNode : SKSpriteNode!
//点击屏幕牵动zombie行走,
//1.获取点击的点的坐标
//2.判断点击的点的坐标和zombie的锚点的位置
//3.用2的两个坐标要计算得到,旋转角度,距离,移动速度.
let duration : TimeInterval = 1
override func didMove(to view: SKView) {
setupNode()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//获取当前点击的点的坐标
let touchs = touches as NSSet
let touch : AnyObject = touchs.anyObject() as AnyObject
let locationPoint = touch.location(in: self)
self.zombieNode.zRotation = zombieRotate(nodePoint: self.zombieNode.position, touchPoint: locationPoint)
//将zombie移动到当前的点
ZombieMoveToPoint(node: self.zombieNode, point: locationPoint)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
//获取当前点击的点的坐标
let touchs = touches as NSSet
let touch : AnyObject = touchs.anyObject() as AnyObject
let locationPoint = touch.location(in: self)
self.zombieNode.zRotation = zombieRotate(nodePoint: self.zombieNode.position, touchPoint: locationPoint)
//将zombie移动到当前的点
ZombieMoveToPoint(node: self.zombieNode, point: locationPoint)
}
}
extension GameTouch {
func setupNode() {
self.backgroundNode = SKSpriteNode(imageNamed: "background1")
backgroundNode.name = "backgroundNode"
backgroundNode.position = CGPoint.zero
backgroundNode.anchorPoint = CGPoint.zero
self.addChild(backgroundNode)
self.zombieNode = SKSpriteNode(imageNamed: "zombie1.png")
zombieNode.name = "zombie"
zombieNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
zombieRun(node: zombieNode)
self.addChild(zombieNode)
}
func zombieRun(node : SKSpriteNode) {
let step1 = SKTexture(imageNamed: "zombie1.png")
let step2 = SKTexture(imageNamed: "zombie2.png")
let step3 = SKTexture(imageNamed: "zombie3.png")
let step4 = SKTexture(imageNamed: "zombie4.png")
let step5 = SKTexture(imageNamed: "zombie3.png")
let step6 = SKTexture(imageNamed: "zombie2.png")
let stepArray = [step1,step2,step3,step4,step5,step6]
let runRightAction = SKAction.animate(with: stepArray, timePerFrame: 0.15)
let runForever = SKAction.repeatForever(runRightAction)
node.run(runForever)
}
func ZombieMoveToPoint(node : SKSpriteNode ,point : CGPoint) {
let move = SKAction.move(to: point, duration: duration)
node.run(move)
}
func zombieRotate(nodePoint : CGPoint, touchPoint : CGPoint) -> CGFloat {
//获取到当前点击的点的坐标之后, 计算两者之间的距离
let dx = touchPoint.x - nodePoint.x
let dy = touchPoint.y - nodePoint.y
if (dx > 0 && dy > 0) { //第一象限
return atan(dy/dx)
}else if (dx < 0 && dy > 0){//第二象限
return atan(dx/(-dy)) + CGFloat.pi * 0.5
}else if (dx < 0 && dy < 0){//第三象限
return atan(dy/dx) + CGFloat.pi
}else {//第四象限
return CGFloat.pi * 2 - atan((-dy)/dx)
}
}
}
这里面用了一些三角函数的简单只是去控制角度.
zombie旋转的处理 :
- 我的做法和原书教材有点不一样,我以x正方向为固定参考点.方便求角度
- 锚点与触摸的点,两点之间可以求x和y的差值.然后用这两个差值可以求出两点之间的角度.
- 对比四个不同坐标象限的特点.然后做一些逻辑判断.