Sprite Kit如何更新按钮上的图像?
问题描述:
我是Swift和Sprite Kit的新手。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
}
- 有没有一种方法,我的故事板上添加一个UIButton,比连接 GameScene,迅速与故事板? (以编程方式添加子节点 可能确实很难)
- 节点的CGPoint基于什么?目前的UIView?
- 如何编程更改按钮的图像(使用 SpriteKit节点SWIFT)与其他图像举例来说,如果我有图片: dice1,dice2,dice3 ...
这是客观C代码:
NSString *fileName = [NSString stringWithFormat:@"dice%d.png", num];
// Setting the uiimageview to the appropriate image
self.rollButton.image = [UIImage imageNamed:fileName];
我没有找到如何设置从storyborard按钮,也比使用uiviewcontrollers到每个新创建的GameScene任何很好的例子,
答
首先,创建一个你想要的图像rray按钮有:
let arrayOfImages = [
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png",
"image6.png"
]
然后初始化按键精灵,并给它一个纹理开始:
var rollButton = SKSpriteNode()
rollButton.texture = SKTexture(imageNamed: arrayOfImages[0])
然后,每次changeButtonImage()
被调用时,产生一个随机数并更改按钮的质感:
var randomNumberBetween0And5 = Int(arc4random_uniform(6))
rollButton.texture = SKTexture(imageNamed: arrayOfImages[randomNumberBetween0And5])
答
如果你想建立一个按钮或使用通用的开关,你应该试试这个控制我做了,利用它非常直截了当: 你刚才初始化按钮类型/开关你想(ColoredSprite,纹理或纯文字)
let control = TWButton(normalColor: SKColor.blueColor(), highlightedColor: SKColor.redColor(), size: CGSize(width: 160, height: 80))
和初始化后添加一个闭合它(像addTargetForSelector上的UIButton)
control.addClosureFor(.TouchUpInside, target: self, closure: { (scene, sender) ->() in
scene.testProperty = "Changed Property"
})
}
这它!有一个在GitHub的页面上的自述节的更多信息:https://github.com/txaidw/TWControls
但是,如果你想在一个特定的节点来实现这里是我如何做:
internal override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let touchPoint = touch.locationInNode(self.parent)
if self.containsPoint(touchPoint) {
self.touchLocationLast = touchPoint
touchDown()
}
}
internal override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let touchPoint = touch.locationInNode(self.parent)
self.touchLocationLast = touchPoint
}
internal override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let touchPoint = touch.locationInNode(self.parent)
if let lastPoint = self.touchLocationLast where self.containsPoint(lastPoint) {
// Ended inside
touchUpInside()
}
else {
// Ended outside
touchUpOutside()
}
}