我想知道如何检查哪个图像已分配给SKSpriteNode。
这是我的代码: 更新了feb11
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.contactDelegate = self
}//enddidMoveToView
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
print("hello")
var ball = SKSpriteNode()
for touch in touches {
let location = touch.locationInNode(self)
//calls a ball with a randomImgColor
ball = SKSpriteNode(imageNamed:"ball\(arc4random_uniform(3))")
ball.xScale = 0.1
ball.yScale = 0.1
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2.5)
ball.position = location
if ball == SKSpriteNode(imageNamed:"ball0") {
print("the red ball was assigned")
} else if ball == SKSpriteNode(imageNamed:"ball1") {
print("the green ball was assigned")
} else if ball == SKSpriteNode(imageNamed:"ball2") {
print("the blue ball was assigned")
}
self.addChild(ball)
}//ends touch
}//endtouchesBegan
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}//end GameScene
答案 0 :(得分:0)
我有一个解决方案,但它可能不是你想要的。由于您通过将随机字符串传递到SKSpriteNode
来创建图像,因此您可以将字符串存储在变量中,并将SKSpriteNotes
.name
属性设置为同样的事物然后检查name的值。这样可以省去创建要检查的实例的麻烦:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
var ball = SKSpriteNode() // in your for loop!
let location = touch.locationInNode(self)
let random = "ball\(arc4random_uniform(3))" // <-- notice
ball = SKSpriteNode(imageNamed:random)
ball.xScale = 0.1
ball.yScale = 0.1
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height / 2.5)
ball.name = random // <-- set name == to your ball type
ball.position = location
// safely unwrap ball name
guard let ballName = ball.name else {
return
}
print(ballName)
// check ball name
if ballName == "ball0" {
print("the red ball was assigned")
} else if ballName == "ball1" {
print("the green ball was assigned")
} else if ballName == "ball2" {
print("the blue ball was assigned")
}
self.addChild(ball)
}
}//ends touch
原帖:
你的条件逻辑混淆了,你错过了大括号:
if ball == SKSpriteNode(imageNamed:"ball0") {
print("the red ball was assigned")
} else if ball == SKSpriteNode(imageNamed:"ball1") {
print("the green ball was assigned")
} else if ball == SKSpriteNode(imageNamed:"ball2") {
print("the blue ball was assigned")
}
虽然我无法确定您的意图是什么,但我认为您希望您的for循环中的条件语句正确无误?
for touch in touches {
let location = touch.locationInNode(self)
//calls a ball with a randomImgColor
ball = SKSpriteNode(imageNamed:"ball\(arc4random_uniform(3))")
ball.position = location
if ball == SKSpriteNode(imageNamed:"ball0") {
print("the red ball was assigned")
} else if ball == SKSpriteNode(imageNamed:"ball1") {
print("the green ball was assigned")
} else if ball == SKSpriteNode(imageNamed:"ball2") {
print("the blue ball was assigned")
}
self.addChild(ball)
}