[英]Move object while holding button in Swift
我有一個小的太空入侵者游戲,我添加了兩個按鈕leftButton
和rightButton
,我希望只要其中一個按鈕被觸摸並按正確的方向移動, ship
就會移動。
我讓它向正確的方向移動,但我必須反復點擊按鈕,但我希望ship
在玩家按住按鈕時移動。
為簡單起見,我只發布左按鈕的代碼,因為我認為編碼其他按鈕的方式是相同的:
class GameScene: SKScene {
var leftButton = SKSpriteNode()
var ship = SKSpriteNode()
override func didMove(to view: SKView) {
leftButton = self.childNode(withName: "left") as! SKSpriteNode
ship = self.childNode(withName: "player") as! SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let pointTouched = touch.location(in: self)
if leftButton.contains(pointTouched) {
player.position.x -= 30
}
}
}
}
為此使用Action。 還有其他方法可以實現這一點,但這對您有用。
首先添加一個func moveBy
,它取你希望你的船的方向和一個key: String
。 您將在稍后的touchesBegan
使用這些。
func moveShip (moveBy: CGFloat, forTheKey: String) {
let moveAction = SKAction.moveBy(x: moveBy, y: 0, duration: 1)
let repeatForEver = SKAction.repeatForever(moveAction)
let seq = SKAction.sequence([moveAction, repeatForEver])
//run the action on your ship
player.run(seq, withKey: forTheKey)
}
的touchesBegan:
if leftButton.contains(pointTouched) {
moveShip(moveBy: -30, forTheKey: "left")
}
if rightButton.contains(pointTouched) {
moveShip(moveBy: 30, forTheKey: "right")
}
編輯:
touchesEnded:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
player.removeAction(forKey: "left")
player.removeAction(forKey: "right")
}
您可以使用SKAction:`
class GameScene: SKScene {
var leftButton = SKSpriteNode()
var ship = SKSpriteNode()
let Left = SKAction.repeatForever(
SKAction.sequence([
SKAction.wait(forDuration: 0.5),
SKAction.run({
SKAction.move(by: CGVector(dx: -30, dy: 0), duration:0.5)
} )]))
//This SKAction will repeat it self forever, until the action is removed. It's build from a sequence of to other actions, move and wait.
override func didMove(to view: SKView) {
leftButton = self.childNode(withName: "left") as! SKSpriteNode
ship = self.childNode(withName: "player") as! SKSpriteNode
}
override func touchesBegan(_ touches: Set<UITouch>, with event:UIEvent?) {
for touch: AnyObject in touches {
let pointTouched = touch.location(in: self)
if leftButton.contains(pointTouched) {
self.run(Left, withKey: "left")
//Keys will help you remove actions, as well as to remove certain actions, sorting them by group
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.removeAction(forKey: "left")
}
}
更新你對按鈕進行編碼的方式非常奇怪我這樣做它總是有效:`
if let touch = touches.first{
let pos = touch.location(in: self)
let node = self.atPoint(pos)
if node == button {
if let view = view {
//your code
}
}}
`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.