Reputation: 293
Hi I am currently working on a platforming game for 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
?
If possible I would like to know both methods or the most efficient.
Thanks in advance!!!!
-Matt A.
Upvotes: 0
Views: 925
Reputation: 293
Here is what I did: When touchesBegan my player would go left. Then I used touchesEnded to tell my player to stop.
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!")
}
}
}
Upvotes: 0
Reputation: 521
The common strategy to handle user press event is using system provided 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
}
}
}
Upvotes: 3