我的 Pong 版本有问题。 当我输入这段代码时,球不会在屏幕上移动。 问题出在哪儿? 请帮助我!
class GameScene: SKScene {
var ball = SKSpriteNode()
var enemy = SKSpriteNode()
var main = SKSpriteNode()
override func didMove(to view: SKView) {
ball = self.childNode(withName: "ball") as! SKSpriteNode
enemy = self.childNode(withName: "enemy") as! SKSpriteNode
main = self.childNode(withName: "main") as! SKSpriteNode
ball.physicsBody?.applyImpulse(CGVector(dx: 20, dy: 20))
let border = SKPhysicsBody(edgeLoopFrom: self.frame)
border.friction = 0
border.restitution = 1
self.physicsBody = border
}
}
最佳答案
你知道这行代码
ball.physicsBody?.applyImpulse(CGVector(dx: 20, dy: 20))
表示
“如果球的属性physicsBody
不为nil
,调用方法applyImpulse()
”
不是吗?好的。如果 physicsBody
是 nil
,这段代码会做什么?是的,它什么都不做。那么,您是否在执行此代码时检查过 physicsBody
不是 nil
?
根据属性physicsBody
的文档:
The default value is nil, which indicates that the node does not participate in the physics simulation at all. If a physics body is provided, when the scene’s physics are simulated, the physics body updates the node’s position and rotates the node.
没有代码显示您在球对象上设置了 physicsBody
。
关于swift - 球在 Pong Clone 中不动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40619797/