2016-09-24 69 views
1
Ghost = SKSpriteNode(imageNamed: "Ghost1") 
    Ghost.size = CGSize(width: 50, height: 50) 
    Ghost.position = CGPoint(x: self.frame.width/2 - Ghost.frame.width, y: self.frame.height/2) 

    Ghost.physicsBody = SKPhysicsBody(circleOfRadius: Ghost.frame.height/1.4) 
    Ghost.physicsBody?.categoryBitMask = PhysicsCatagory.Ghost 
    Ghost.physicsBody?.collisionBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall 
    Ghost.physicsBody?.contactTestBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall | PhysicsCatagory.Score 
    Ghost.physicsBody?.affectedByGravity = false 
    Ghost.physicsBody?.isDynamic = true 

    Ghost.zPosition = 2 


    self.addChild(Ghost) 

在我的應用程序中,我有一個對象在屏幕上移動,它的名稱是「鬼」。我不知道如何設置一個按鈕,將改變代碼說Changeable Image

Ghost = SKSpriteNode(imageNamed: "Ghost2") 

,而不是

Ghost = SKSpriteNode(imageNamed: "Ghost1") 

回答

3

要改變圖像的SKSpriteNode您分配一個不同的質地:

Ghost.texture = SKTexture(imageNamed:"Ghost2") 

注意:您應該使用小寫字母作爲變量名以區分它們與類名。

包含Button和您的Ghost的示例實現將如下所示,並在右上角創建一個紅色按鈕。看到按鈕和幻影的聲明現在發生在didMoveToView之外,以便稍後可以引用這些變量,當用戶點擊屏幕時。

class ButtonGhostScene: SKScene { 
    var button: SKNode! = nil 
    var ghost: SKSpriteNode! = nil 

    override func didMove(to view: SKView) { 
     button = SKSpriteNode(color: SKColor.redColor(), size: CGSize(width: 100, height: 44)) 
     button.position = CGPoint(x:self.size.width, y:self.size.height) 

     ghost = SKSpriteNode(imageNamed: "Ghost1") 
     ghost.size = CGSize(width: 50, height: 50) 
     ghost.position = CGPoint(x: self.frame.width/2 - Ghost.frame.width, y: self.frame.height/2) 
     ghost.physicsBody = SKPhysicsBody(circleOfRadius: Ghost.frame.height/1.4) 
     ghost.physicsBody?.categoryBitMask = PhysicsCatagory.Ghost 
     ghost.physicsBody?.collisionBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall 
     ghost.physicsBody?.contactTestBitMask = PhysicsCatagory.Ground | PhysicsCatagory.Wall | PhysicsCatagory.Score 
     ghost.physicsBody?.affectedByGravity = false 
     ghost.physicsBody?.isDynamic = true 
     ghost.zPosition = 2 

     self.addChild(ghost) 
     self.addChild(button) 
    } 

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     // Loop over all the touches in this event 
     for touch: AnyObject in touches { 
      // Get the location of the touch in this scene 
      let location = touch.location(in: self) 
      // Check if the location of the touch is within the button's bounds 
      if button.containsPoint(location) { 
       ghost.texture = SKTexture(imageNamed:"Ghost2") 
      } 
     } 
    } 
} 

當用戶點擊屏幕時,會執行touchesBegan並檢查用戶點擊是否在按鈕上。

+0

不知道是誰投了你的票,但這絕對是一個答案,我只想談談更多關於按鈕過程,因爲這是問題的要求 – Knight0fDragon

+0

@ Knight0fDragon我最初專注於SKTexture,而不是按鈕,然後在投票後改進答案! –

+0

是的我知道,這就是爲什麼我說說更多關於按鈕 – Knight0fDragon