我正在学习SpriteKit,并附有关于简单纸牌游戏的教程。我有一个场景,我放了两张卡,节点。我应该可以点击其中一张卡片,拿起它,移动它,然后放下它。奇怪的是,我可以做到这一点,但通常只有一次。如果我再试一次,它有时会起作用,但很多时候我会得到旋转的沙滩球并且必须反弹模拟器才能让它再次运转。这是一个简单的代码,但我无法弄清楚它为什么会这样做。
enum CardName: Int {
case CreatureWolf = 0,
CreatureBear
}
class Card : SKSpriteNode {
let frontTexture: SKTexture
let backTexture: SKTexture
var largeTexture: SKTexture?
let largeTextureFilename: String
required init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
init(cardNamed: CardName) {
// initialize properties
backTexture = SKTexture(imageNamed: "card_back.png")
switch cardNamed {
case .CreatureWolf:
frontTexture = SKTexture(imageNamed: "card_creature_wolf.png")
largeTextureFilename = "card_creature_wolf_large.png"
case .CreatureBear:
frontTexture = SKTexture(imageNamed: "card_creature_bear.png")
largeTextureFilename = "Card_creature_bear_large.png"
default:
frontTexture = SKTexture(imageNamed: "card_back.png")
largeTextureFilename = "card_back_large.png"
}
// call designated initializer on super
super.init(texture: frontTexture, color: UIColor.whiteColor(), size: frontTexture.size())
// set properties defined in super
userInteractionEnabled = true
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for _ in touches {
zPosition = 15
let liftUp = SKAction.scaleTo(1.2, duration: 0.2)
runAction(liftUp, withKey: "pickup")
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(scene!)
let touchedNode = nodeAtPoint(location)
touchedNode.position = location
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for _ in touches {
zPosition = 0
let dropDown = SKAction.scaleTo(1.0, duration: 0.2)
runAction(dropDown, withKey: "drop")
}
}
}
这里是将卡片放在场景上的代码:
//
// GameScene.swift
// PlanningPoker
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
let wolf = Card(cardNamed: .CreatureWolf)
wolf.position = CGPointMake(400,600)
addChild(wolf)
let bear = Card(cardNamed: .CreatureBear)
bear.position = CGPointMake(600, 600)
addChild(bear)
}
}
任何人都可以帮助我理解为什么会发生这种情况或我如何调试它?我已经在每个触摸*&#39;的开头和结尾添加了打印声明。功能,以确保它按预期(并且它是)通过它们,Xcode没有给我任何警告或错误,我已经对教程的代码进行了27次双重检查确定它匹配(确实如此,除了我必须改变的一些东西,以便将其提升到Swift 2.1)并且它应该正常工作。
由于
答案 0 :(得分:1)
我最好的猜测是不正确的。
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(scene!)
let touchedNode = nodeAtPoint(location)
touchedNode.position = location
}
}
您获得了正确的位置,但您可能无法获得所需的节点。您实际上是在尝试移动调用此方法的节点。没有必要尝试获得不同的节点。
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(scene!)
position = location
}
}
希望这有帮助。