2015-04-03 119 views
0

非常感謝提前。 我試圖在StackOverflow上搜索或只是谷歌它,也許我用錯了關鍵詞或別的東西,我無法找到我的問題的答案。 所以我是iOS新手,我是這麼做的,我在屏幕中間用四種不同顏色(這是一張圖片)設置了一個正方形,每當我點擊屏幕時,它都會旋轉90度。還有更小的球會從屏幕外部以顏色出現,比如紅色的球,綠色的球,藍色的球等。當球以相同的顏色接觸正方形時,得分爲1分。就像遊戲一樣。顏色搭配精靈套件和swift

那麼我應該如何設置不同顏色的方形來實現這一點呢? 我認爲它只能將一種顏色設置爲一個精靈。或者我應該把4個三角形放在一起做廣場?

回答

2

您可以使用以下代碼設置四個彩色Square。

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來測試與每個彩色球碰撞。

+0

謝謝,這對我有用。 – 2015-04-04 14:58:40

1

您可以使用與圖形CGContext相關聯的路徑,描邊和填充功能,並修改下面的代碼以使其在圖像中繪製所需圖案並用顏色填充不同部分。由此產生的UIImage將成爲新雪碧的基礎。請參閱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))!