目前,在我的代码中,我有一个名为SKSpriteNode的球,当它与任何东西接触时,它会随机改变纹理。有4个不同的纹理/图像,每个都有不同颜色的球。我想使用if else语句来检查球是否等于特定的纹理,这样它就可以执行一个动作。
到目前为止,我已经有了这段代码,但它并没有真正检查球子雪碧图的纹理
func didBeginContact(contact: SKPhysicsContact) {
if ball.texture == SKTexture(imageNamed: "ball2") && platform3.position.y <= 15 {
print("Color is matching")
} else {
print("Not matching")
}
}if platform3.position tion.y <= 25部分可以工作,但代码的ball.texture部分不会检查球的纹理。
发布于 2016-08-29 08:16:01
为球指定颜色时设置用户数据。
ball.userData = ["color": 1]
// later you can check
if (ball.userData["color"] == 1) {这才是正确的做法。比较整数会更快。
发布于 2016-08-29 08:28:18
ColorType
您可以使用枚举来表示可能的颜色
enum ColorType: String {
case red = "redBall", green = "greenBall", blue = "blueBall", white = "whileBall"
}每个枚举案例的原始值都是图像的名称。
球
接下来,声明您的sprite类,如下所示。如您所见,我正在跟踪当前的colorType。此外,只要更改colorType,就会为精灵指定一个新的纹理
class Ball: SKSpriteNode {
var colorType: ColorType {
didSet {
self.texture = SKTexture(imageNamed: colorType.rawValue)
}
}
init(colorType: ColorType) {
self.colorType = colorType
let texture = SKTexture(imageNamed: colorType.rawValue)
super.init(texture: texture, color: .clearColor(), size: texture.size())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}用法
let ball = Ball(colorType: .blue)
if ball.colorType == .blue {
print("Is blue")
}
ball.colorType = .greenhttps://stackoverflow.com/questions/39196953
复制相似问题