[英]How do create a button using Sprite Kit and Swift?
Hi I am currently working on a platforming game for iOS. 嗨,我目前正在为iOS开发平台游戏。 I would like to be able to move my character left or right by the press of a button. 我希望能够通过按下按钮左右移动我的角色。 How is it that I can create a button? 如何创建按钮? Do I use UIKit
or an SKNode
? 是否使用UIKit
或SKNode
?
If possible I would like to know both methods or the most efficient. 如果可能,我想了解两种方法或最有效的方法。
Thanks in advance!!!! 提前致谢!!!!
-Matt A. 玛特·A
The common strategy to handle user press event is using system provided func touchesBegan:touches withEvent:event
: 处理用户新闻事件的常用策略是使用系统提供的func touchesBegan:touches withEvent:event
:
//add trigger node into your scene
let triggerNode = SKSpriteNode(texture: SKTextureAtlas(named: "scenery.atlas").textureNamed(soundImg))
triggerNode.name = "TriggerNodeName"
triggerNode.zPosition = 10
addChild(triggerNode)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in: self)
let touchNode = atPoint(location)
print("\(touchNode.name)")
if touchNode.name == "TriggerNodeName"{
//write your logic here
...
return
}
}
}
Here is what I did: When touchesBegan my player would go left. 这是我的工作:当touchesBegan开始时,我的播放器将向左走。 Then I used touchesEnded to tell my player to stop. 然后,我使用touchesEnded告诉播放器停止播放。
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in: self)
let touchNode = atPoint(location)
print("\(touchNode.name)")
if touchNode.name == "Button"{
//write your logic here
thePlayer.goLeft()
print("Pressed!")
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in: self)
let touchNode = atPoint(location)
print("\(touchNode.name)")
if touchNode.name == "Button"{
//write your logic here
thePlayer.stop()
print("Pressed!")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.