### 工欲善其事,必先利其器
有时候学习如何应用第三方库是非常重要的,因为我们不用再自己重复造*,在这里,我们就把原先利用重力感应来操控飞机改为用游戏摇杆joystick来操控,具体的操作如下:
```
// 声明游戏摇杆;
private var joystick:AnalogJoystick! // 游戏摇杆;
```
> 创建函数,新建游戏摇杆节点,并添加到GameScene中
```
//MARK:-// 加入游戏手柄
func createJoyStick(){
joystick = AnalogJoystick(diameter: CGFloat(250.0)) // 摇杆直径
joystick.stick.image = UIImage(named: "jStick") // 摇杆图
joystick.substrate.image = UIImage(named: "jSubstrate") // 摇杆背景图
joystick.zPosition = 1
joystick.position = CGPoint(x: -380.0, y: -720.0)
self.addChild(joystick)
joystick.alpha = 0.8
// 操控刚开始
joystick.beginHandler = { [unowned self] in
guard let sprite = self.playerNode else {
return
}
print("begin",sprite);
}
// 追踪操控
joystick.trackingHandler = {[unowned self] data in
guard let sprite = self.playerNode else {
return
}
let x = data.velocity.x * 0.12
let y = data.velocity.y * 0.12
let xPos = sprite.position.x + x
let yPos = sprite.position.y + y
sprite.position = CGPoint(x: xPos, y: yPos) // 更新飞机位置
//sprite.zRotation = data.angular // 飞机角度转向;
}
// 停止摇杆时;
joystick.stopHandler = { [unowned self] in
guard let sprite = self.playerNode else {
return
}
print("stop",sprite);
}
}
```
>在 override func didMove(to view: SKView) {}内加入摇杆函数
```
// 游戏手柄开始
override func didMove(to view: SKView) {
createJoyStick()
}
```
只需要上面这几步,就可以添加酷酷的游戏摇杆了,就这么简单!!!
游戏教学:http://www.iFIERO.com
源码传送门:https://github.com/apiapia/SpaceBattleSpriteKitGame