首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swift -如何检查是否将sprite分配给了某些图像

Swift -如何检查是否将sprite分配给了某些图像
EN

Stack Overflow用户
提问于 2016-08-29 08:11:38
回答 2查看 419关注 0票数 0

目前,在我的代码中,我有一个名为SKSpriteNode的球,当它与任何东西接触时,它会随机改变纹理。有4个不同的纹理/图像,每个都有不同颜色的球。我想使用if else语句来检查球是否等于特定的纹理,这样它就可以执行一个动作。

到目前为止,我已经有了这段代码,但它并没有真正检查球子雪碧图的纹理

代码语言:javascript
复制
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部分不会检查球的纹理。

EN

回答 2

Stack Overflow用户

发布于 2016-08-29 08:16:01

为球指定颜色时设置用户数据。

代码语言:javascript
复制
ball.userData = ["color": 1]
// later you can check
if (ball.userData["color"] == 1) {

这才是正确的做法。比较整数会更快。

票数 1
EN

Stack Overflow用户

发布于 2016-08-29 08:28:18

ColorType

您可以使用枚举来表示可能的颜色

代码语言:javascript
复制
enum ColorType: String {
    case red = "redBall", green = "greenBall", blue = "blueBall", white = "whileBall"
}

每个枚举案例的原始值都是图像的名称。

接下来,声明您的sprite类,如下所示。如您所见,我正在跟踪当前的colorType。此外,只要更改colorType,就会为精灵指定一个新的纹理

代码语言:javascript
复制
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")
    }
}

用法

代码语言:javascript
复制
let ball = Ball(colorType: .blue)
if ball.colorType == .blue {
    print("Is blue")
}
ball.colorType = .green
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39196953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档