与 sprite 套件和 swift 颜色匹配

color match with sprite kit and swift

非常感谢。 我试图在 Whosebug 或 google 上搜索它,也许我使用了错误的关键词或其他东西,我无法找到我的问题的答案。 所以我是 iOS 编程的新手,这是我所做的,我在屏幕中间设置了一个正方形,有 4 种不同的颜色(这是一张图片),每次我点击屏幕时,它都会旋转 90 度。还有一些较小的球会从屏幕外飞来,颜色相同,如红球、绿球、蓝球等。当球接触到相同颜色的方块时,得一分。就像游戏一样。

那么我应该如何设置不同颜色的正方形来完成这个呢? 我以为它只能为一个精灵设置一种颜色。或者我应该把 4 个三角形拼成正方形?

您可以使用与图形关联的路径、描边和填充函数 CGContext 并修改下面的代码,使其在图像中绘制您想要的图案并用颜色填充不同的部分。生成的 UIImage 将成为新 Sprite 的基础。见 CGContext Documentation

    import CoreImage
    import CoreGraphics
    int width = 100
    int height = 100
    var colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedFirst.rawValue)
    var ctx = CGBitmapContextCreate(nil, width, height, 8, 0, colorspace, bitmapInfo)!
    .
    . draw into your ctx (context) here
    .
    var image = UIImage(CGImage: CGBitmapContextCreateImage(ctx))!

您可以使用以下代码设置四色方块。

class FourColorSquare : SKNode {

    private var colors : [UIColor] = []
    private var size : CGSize!


    init(colors : [UIColor], size: CGSize) {
        super.init()
        self.colors = colors
        self.size = size
        self.setupNodes()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    func setupNodes() {

        let node1 = SKSpriteNode(color: colors[0], size: self.size)
        node1.position = CGPointMake(0, 0)
        node1.anchorPoint = CGPointMake(1, 0)
        addChild(node1)

        let node2 = SKSpriteNode(color: colors[1], size: self.size)
        node2.position = CGPointMake(0, 0)
        node2.anchorPoint = CGPointMake(0, 0)
        addChild(node2)

        let node3 = SKSpriteNode(color: colors[2], size: self.size)
        node3.position = CGPointMake(0, 0)
        node3.anchorPoint = CGPointMake(0, 1)
        addChild(node3)

        let node4 = SKSpriteNode(color: colors[3], size: self.size)
        node4.position = CGPointMake(0, 0)
        node4.anchorPoint = CGPointMake(1, 1)
        addChild(node4)
    }

    func rotate(angle : CGFloat, animated : Bool) {
        var rotateAction : SKAction!

        if animated {
            rotateAction = SKAction.rotateByAngle(angle, duration: 0.6)
        }
        else {
            rotateAction = SKAction.rotateByAngle(angle, duration: 0)
        }
        for node in self.children as [SKSpriteNode] {

            node.runAction(rotateAction)
        }
    }
}

你可以这样使用它

let colors = FourColorSquare(colors: [.redColor(),.greenColor(),.blueColor(),.yellowColor()], size: CGSizeMake(50, 50))
colors.position = CGPointMake(200, 100)
addChild(colors)

colors.rotate(-3.14/2, animated: true)

您可以为 FourColorSquare 中的每个节点设置单独的物理体,以检测与每种颜色的碰撞。每种颜色都应该有一个单独的 categoryBitMask 来测试与每个彩色球的碰撞。