I am playing around trying to learn swift and I am trying to have a brick sprite placed every time a person's touch ends. I'm new and not quite sure of if or how this is possible with spriteKit. I would like to have the brick interact with physics so if there is another way to do this without creating new sprites that would work as well
Asked
Active
Viewed 41 times
1 Answers
0
Just add the method touchesEnded
to your class, create a new SpriteNode and add it to your scene. Something like this:
func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let yourNode = SKSpriteNode(imageNamed: "brick.png") //or the name of the brick texture file, if you have one
yourNode.position = CGPoint(x: 100, y: 100)
self.addChild(yourNode)
}
Here we added the node to (100,100), but you could add it to the location of the touch, adding this inside the method:
for touch in touches {
let location = touch.location(in: self)
yourNode.position = location
}
Remember to import SpriteKit
to your class.

Maria
- 134
- 6
-
1Oh, okay. In this case, try something like this: https://stackoverflow.com/a/39020344/11535394 It is in Swift 3.0 but the idea is the same, and probably only a few things changed for Swift 5. – Maria Apr 30 '20 at 21:49
-
1It probably would. You just have to check if the touch location is inside the position of any of the array's nodes (use `.contains()` for that), then move that specific node. – Maria Apr 30 '20 at 21:54
-
Thank you so much for the reply, I never have been much good at asking questions and the problem is that I would like to be able to use the nodes outside of that func. For example, I want to be able to tap on it and drag to change its position and I can't access the variable from the touches moved func. Thank you again! EDIT: I am thinking of creating a global arrayList and a function that adds brick sprites to that arraylist and have the touches functions simply refer to a specific item in the arraylist, would that work? – User9123 Apr 30 '20 at 21:54