您可以从我的代码中看到,对象是否在移动取决于用户是否已注册长按。如果对象超出视野,我想在testPosition函数中执行代码,该函数只是将其重新放置在视野中。我不知道在哪里使用此功能。如果我以长按手势应用它,则只有在长按开始或结束时才进行测试,因此,如果用户一直按住,则该功能将不会执行,并且该对象也不会重新定位。我也尝试了while语句,但它们似乎也不起作用。欢迎提出任何建议,我对Swift还是一个新手,感谢您的帮助。
import SpriteKit
class GameScene: SKScene {
let square = SKSpriteNode(imageNamed: "square")
override func didMove(to view: SKView) {
setScene()
}
@objc func press(_ sender: UILongPressGestureRecognizer) {
sender.minimumPressDuration = 0.01
if sender.state == .ended {
physicsWorld.gravity = CGVector(dx: 0, dy: -1.7)
print ("press ends")
square.run(SKAction.applyForce(CGVector(dx: 0, dy: -275), duration: 0.3))
} else if sender.state == .began {
square.run(SKAction.applyForce(CGVector(dx: 0, dy: 275), duration: 0.3))
physicsWorld.gravity = CGVector(dx: 0, dy: 1.7)
print ("pressed")
} else {
return
}
}
func testPosition() {
if square.position.y < frame.minY {
print("too low")
square.position.y = frame.minY + 100
} else if square.position.y > frame.maxY {
print("too high")
square.position.y = frame.maxY - 100
} else {
return
}
}
func setScene() {
backgroundColor = UIColor(red: 238/255, green: 12/255, blue: 95/255, alpha: 1.0)
square.color = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1.0)
square.size = CGSize(width: frame.size.width/20, height: frame.size.width/20)
square.position = CGPoint(x: frame.midX - 200, y: frame.midY+150)
addChild(square)
square.physicsBody = SKPhysicsBody(rectangleOf: square.size)
square.physicsBody?.categoryBitMask = PhysicsCategories.squareCategory
physicsWorld.gravity = CGVector(dx: 0, dy: -1.7)
square.physicsBody?.affectedByGravity = true
view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press)))
}
}
如下使用计划的计时器重复检查,
对于[SpriteKit]
// In the begin of Long Press, Call the following "startPositionChecking" Function
private func startPositionChecking() {
let wait: SKAction = SKAction.wait(forDuration: 0.5) // ex: Each 0.5 Second
let checkingAction: SKAction = SKAction.run {
self.testPosition()
}
let sequence: SKAction = SKAction.sequence([wait, checkingAction])
let checkingTimer = SKAction.repeatForever(sequence)
self.run(checkingTimer, withKey: "checkingTimer")
}
// In the End of Long Press, Call the following "endPositionChecking" Function
private func endPositionChecking() {
self.removeAction(forKey: "checkingTimer")
}
对于[SWIFT]
var checkingTimer: Timer?
private func startPositionChecking() {
checkingTimer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(testPosition), userInfo: nil, repeats: true)
}
private func endPositionChecking() {
checkingTimer?.invalidate()
}