我有一个游戏(比如涂鸦跳转),我的玩家会击中物体并从它们身上反弹以前进并获得积分。当玩家击中所述对象时,它们应该消失(.removeFromParent()),因为它在GameScene中的一个函数中调用,并且在它自己的单独类中。谁能告诉我我做错了什么?
这是我的GameScene代码:
func createSnowAtPosition(position: CGPoint) -> SKNode {
var sprite: SKSpriteNode!
sprite = SKSpriteNode(imageNamed: "icons_winter_09")
let node = Snowflake()
let position = CGPoint(x: position.x, y: position.y)
node.position = position
node.name = "SNOW"
node.addChild(sprite)
sprite.physicsBody?.affectedByGravity = false
sprite.physicsBody?.categoryBitMask = snowCategory
sprite.physicsBody?.collisionBitMask = playerCategory
sprite.physicsBody = SKPhysicsBody(circleOfRadius: snow.size.width / 7)
sprite.physicsBody?.dynamic = false
return node
}
func didBeginContact(contact: SKPhysicsContact) {
if player.physicsBody?.velocity.dy < 0 {
// 2
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 250.0)
// Play sound
runAction(starSound) {
snow.removeFromParent()
}
if snow.position.y < player.position.y {
let pointsLabel = childNodeWithName("scoreLabel") as! Points
pointsLabel.increment()
}
}
这是我的单独类的代码:
import Foundation
import SpriteKit
let snow = SKSpriteNode(imageNamed: "icons_winter_09")
class Snowflake: SKSpriteNode {
init() {
let size = CGSizeMake(40, 50)
super.init(texture: nil, color: UIColor.clearColor(), size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func loadBodyWithSize(size: CGSize) {
snow.physicsBody?.affectedByGravity = false
snow.physicsBody?.categoryBitMask = snowCategory
snow.physicsBody?.collisionBitMask = playerCategory
snow.physicsBody = SKPhysicsBody(circleOfRadius: snow.size.width / 3)
}
func createSnowsAtPosition() {
snow.name = "snow"
snow.position = CGPointMake(50, 200)
snow.physicsBody?.dynamic = false
snow.physicsBody?.usesPreciseCollisionDetection = true
addChild(snow)
}
}
答案 0 :(得分:0)
在开始设置其属性之前定义物理主体,在定义物理主体之前也不要添加节点,所以:
let node = Snowflake()
let position = CGPoint(x: position.x, y: position.y)
node.position = position
node.name = "SNOW"l
sprite.physicsBody?.affectedByGravity = false
sprite.physicsBody?.categoryBitMask = snowCategory
sprite.physicsBody?.collisionBitMask = playerCategory
sprite.physicsBody = SKPhysicsBody(circleOfRadius: snow.size.width / 7)
sprite.physicsBody?.dynamic = false
addNode(node)
return node