swift - Sprite Kit 如何更新按钮上的图像?

标签 swift storyboard sprite-kit xcode-storyboard

我是 Swift 和 Sprite Kit 的新手。

我想在 MyScene.swift 中创建一个具有特定图像的按钮。每次单击按钮时,我都想用新图像更改按钮图像。 我该怎么做?

GameScene.swift

class GameScene: SKScene {
var rollButton:SKSpriteNode = SKSpriteNode(imageNamed: "dice1.png")

 override func didMoveToView(view: SKView) {

 rollButton.position = CGPoint(x: 79, y: 290) //this position is based to what? Is there an easier way to put a button using storyborard

  rollButton.setScale(0.5) //what does setScale mean?
self.addChild(rollButton)
}

 override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
  for touch: AnyObject in touches {
    if CGRectContainsPoint(rollButton.frame, touch.locationInNode(self)) {
      changeButtonImage()
    }
   }
 }

func changeButtonImage() {
//radom get value beteween 1 - 6
change the rollButton image with a new value??? //how to do that
}
  1. 有没有办法在 Storyboard 上添加一个 UIButton 然后连接 GameScene,快速处理那个 Storyboard? (添加子节点 以编程方式可能真的很难)
  2. 一个节点的CGPoint是基于什么?当前的 UIView?
  3. 如何以编程方式更改按钮的图像(快速使用 SpriteKit 节点)与其他图像,例如我有图像: 骰子 1、骰子 2、骰子 3……

这是 objective-c 代码:

NSString *fileName = [NSString stringWithFormat:@"dice%d.png", num];
// Setting the uiimageview to the appropriate image
self.rollButton.image = [UIImage imageNamed:fileName];

我没有找到任何关于如何从 Storyboard设置按钮以及如何将 uiviewcontrollers 用于创建的每个新 GameScene 的好例子,

最佳答案

首先,创建一个包含您希望按钮具有的图像的数组:

let arrayOfImages = [
  "image1.png",
  "image2.png",
  "image3.png",
  "image4.png",
  "image5.png",
  "image6.png"
]

然后初始化按钮 Sprite 并给它一个纹理开始:

var rollButton = SKSpriteNode()
rollButton.texture = SKTexture(imageNamed: arrayOfImages[0])

然后,每次调用 changeButtonImage() 时,生成一个随机数并更改按钮的纹理:

var randomNumberBetween0And5 = Int(arc4random_uniform(6))
rollButton.texture = SKTexture(imageNamed: arrayOfImages[randomNumberBetween0And5])

关于swift - Sprite Kit 如何更新按钮上的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994491/

相关文章:

ios - Swift 3 中的背景音乐

wpf - 在另一个 Storyboard时间线中启动 Storyboard

iOS 在 swift 主 StoryBoard 之前创建一个欢迎页面

多次注册 Swift SpriteKit 碰撞

swift - 如何让 SKAction 运行的函数更新资金 Int?

ios - 当不可见单元格时获取单元格 Collection View 的值

ios - Swift 动态变量名称取决于值

iphone - 如何检测是否在 xcode 7 中点击了表格 View 单元格

ios5 - 如何将 ios 5 Storyboard从 ipad 转换为 iphone?

ios - SpriteKit 和 Swift 中的 isDynamic 和 contactDelegate