我在屏幕中间有一张汽车的图像。因此,当我按下屏幕时,我希望它从汽车变为平面图像,当我放开屏幕时,我希望它回到汽车图像。我现在的代码一直在反复生成图像,它们不会在两个图像之间切换。这是我的代码:
func addCar() {
let redCar = SKSpriteNode(imageNamed: "redC")
redCar.position = CGPointMake(self.size.width / 2, self.size.height / 7)
redCar.zPosition = 42
addChild(redCar)
redCar.physicsBody = SKPhysicsBody(circleOfRadius: 20)
redCar.physicsBody?.allowsRotation = false
redCar.physicsBody?.affectedByGravity = false
redCar.physicsBody?.contactTestBitMask = RedCategory | RedCarCategory
redCar.physicsBody?.categoryBitMask = RedCarCategory
redCar.physicsBody?.collisionBitMask = RedCarCategory
}
func addBluePlane() {
let bluePlane = SKSpriteNode(imageNamed: "blueC")
bluePlane.position = CGPointMake(self.size.width / 2, self.size.height / 7)
bluePlane.zPosition = 43
addChild(bluePlane)
bluePlane.physicsBody = SKPhysicsBody(circleOfRadius: 20)
bluePlane.physicsBody?.allowsRotation = false
bluePlane.physicsBody?.affectedByGravity = false
bluePlane.physicsBody?.contactTestBitMask = GreenCategory | BluePlaneCategory
bluePlane.physicsBody?.categoryBitMask = BluePlaneCategory
bluePlane.physicsBody?.collisionBitMask = BluePlaneCategory
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
if let touch = touches.first {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)
addCar()
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
addBluePlane()
}
答案 0 :(得分:3)
我没有专门的SpriteKit经验,但似乎您一次又一次地创建和添加节点。您应该将redCar
声明为实例变量,而不是类中的局部变量。同样适用于bluePlane
。
class YourClass {
let redCar = SKSpriteNode(imageNamed: "redC")
let bluePlane = SKSpriteNode(imageNamed: "blueC")
func addCar() {
bluePlane.removeFromParent()
addChild(redCar)
//rest goes here. dont create another redCar object
//.......
}
func addBluePlane() {
redCar.removeFromParent()
addChild(bluePlane)
//rest goes here. dont create another bluePlane object
//.......
}
}
答案 1 :(得分:-1)
搞定了!我就这样做了:
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 node = self.nodeAtPoint(location)
addCar()
bluePlane.removeFromParent()
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
addBluePlane()
redCar.removeFromParent()
}