作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我是 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
}
这是 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/
我是一名优秀的程序员,十分优秀!