我想让SKSpriteNode
继续在屏幕上移动并永远与边缘反弹。所以我设置边缘的物理学:
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
physicsWorld.gravity = CGVectorMake(0, 0)
然后是精灵的物理学:
ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
ball.size = CGSizeMake(30, 30)
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
ball.physicsBody?.allowsRotation = false
ball.physicsBody?.restitution = 1.0
ball.physicsBody?.linearDamping = 0.0
ball.physicsBody?.friction = 0.0
ball.physicsBody?.applyImpulse(CGVectorMake(10, -10))
self.addChild(ball)
问题是精灵不受物理影响,并且停留在屏幕中央。我做错了什么?
答案 0 :(得分:3)
在你施加冲动之前,你需要将球添加到你的场景中。
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
physicsWorld.gravity = CGVectorMake(0, 0)
let ball = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(30, 30))
ball.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
ball.physicsBody?.allowsRotation = false
ball.physicsBody?.restitution = 1.0
ball.physicsBody?.linearDamping = 0.0
ball.physicsBody?.friction = 0.0
self.addChild(ball)
ball.physicsBody?.applyImpulse(CGVectorMake(10, -10))
}
}