SpriteKit手機遊戲搖桿JoyStick的使用 -- by iFIERO遊戲開發教程
阿新 • • 發佈:2018-07-27
tick eat self. idm rac child lar 重要 sce
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()
}
```
只需要上面這幾步,就可以添加酷酷的遊戲搖桿了,就這麽簡單!!!
### 工欲善其事,必先利其器
有時候學習如何應用第三方庫是非常重要的,因為我們不用再自己重復造輪子,在這裏,我們就把原先利用重力感應來操控飛機改為用遊戲搖桿joystick來操控,具體的操作如下:
```
// 聲明遊戲搖桿;
private var joystick:AnalogJoystick! // 遊戲搖桿;
```
> 創建函數,新建遊戲搖桿節點,並添加到GameScene中
```
//MARK:-// 加入遊戲手柄
func createJoyStick(){
joystick = AnalogJoystick(diameter: CGFloat(250.0)) // 搖桿直徑
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
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 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
SpriteKit手機遊戲搖桿JoyStick的使用 -- by iFIERO遊戲開發教程