【发布时间】:2017-10-04 20:01:16
【问题描述】:
我必须按下按钮leftbutton, rightbutton,它们都是SKSpriteNode()。
当用户触摸其中一个按钮时,只要用户保持触摸,就会有一艘小船左右移动。
现在我需要一个函数或其他任何东西来一直给我ship.position.x。我坚持试图让它不断地打印位置。每次触摸按钮时我都可以让它打印,但它只打印一次。
在我的didMove 中,我只创建了按钮和飞船。所以应该是无关紧要的。
func moveShip (moveBy: CGFloat, forTheKey: String) {
let moveAction = SKAction.moveBy(x: moveBy, y: 0, duration: 0.09)
let repeatForEver = SKAction.repeatForever(moveAction)
let movingSequence = SKAction.sequence([moveAction, repeatForEver])
ship.run(movingSequence, withKey: forTheKey)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
print("\(ship.position.x)")
for touch: AnyObject in touches {
let pointTouched = touch.location(in: self)
if leftButton.contains(pointTouched) {
// !! I MAKE IT PRINT THE POSITION HERE !!
moveShip(moveBy: -30, forTheKey: "leftButton")
}
else if rightButton.contains(pointTouched) {
moveShip(moveBy: 30, forTheKey: "rightButton")
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first{
let pos = touch.location(in: self)
let node = self.atPoint(pos)
if node == aButton {
} else {
ship.removeAction(forKey: "leftButton")
ship.removeAction(forKey: "rightButton")
}
}
}
在我的代码中,位置仅在触摸开始时打印一次,直到您释放触摸并再次触摸时才打印。有没有办法用我的代码做到这一点?
【问题讨论】:
-
您可以覆盖更新方法。在这种方法中,您应该能够获取您的对象并获取位置!
-
我已经阅读了很多有关此更新方法的信息。我怎样才能覆盖它?当我尝试时,xCode 没有建议更新方法
-
看看Bharath的答案!
-
只在我移动手指时有效,但当我握住它而不移动时,船不断移动但位置只在开始时打印一次..
-
也许你可以设置一个定时器,每0.1秒调用一个函数,这个函数,重置定时器,它会创建一个循环?当您移开手指时,您只需停止计时器
标签: ios swift touch-event viewdidload touchesbegan