下面的简单代码创建一个球(触摸时)并设置物理体以使其下降和反弹。我设置了与框架匹配的界限,希望球在屏幕内保持100%。但是,当运行代码时,球将从屏幕左右移出屏幕。如何将精灵保持在屏幕范围内?
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
if let touch = touches.first {
let location = touch.locationInNode(self)
let ball = SKShapeNode(circleOfRadius: 20)
ball.physicsBody = SKPhysicsBody(circleOfRadius: 20)
ball.physicsBody!.restitution = 0.4
ball.position = location
addChild(ball)
}
}
}