I have an SKSpriteNode in which I've set the centerRect property so that the node can be stretched to appear like a styled line. My intention is for the user to touch the screen, and draw/drag a straight line with the node. The line would pivot around an anchor point to remain straight.
In touchesBegan:, the node is added:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
if let _ = fgNode.childNode(withName: "laser") {
print("already there")
} else {
laser.centerRect = CGRect(x: 0.42857143, y: 0.57142857, width: 0.14285714, height: 0.14285714)
laser.anchorPoint = CGPoint(x: 0, y: 0.5)
laser.position = positionInScene
fgNode.addChild(laser)
}
}
And adjusted in touchesMoved::
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
stretchLaserTo(positionInScene)
}
The node is stretched and rotated with two functions:
func stretchLaserTo(_ point: CGPoint) {
let offset = point - laser.anchorPoint
let length = offset.length()
let direction = offset / CGFloat(length)
laser.xScale = length
rotate(sprite: laser, direction: direction)
}
func rotate(sprite: SKSpriteNode, direction: CGPoint) {
sprite.zRotation = atan2(direction.y, direction.x)
}
I think I'm somewhat on the right track. The line rotates with my touch and expands, however, it's extremely sensitive and doesn't stay with my touch. Maybe I'm going about it wrong. Is there a standard technique for doing something like this?
An example of this working can be seen here: https://imgur.com/A83L45i
I suggest you set anchor point of the sprite to (0, 0), set the sprite's scale to the distance between the sprite's position and the current touch location, and then rotate the sprite.
First, create a sprite and set its anchor point.
let laser = SKSpriteNode(color: .white, size: CGSize(width: 1, height: 1))
override func didMove(to view: SKView) {
laser.anchorPoint = CGPoint(x: 0, y: 0)
addChild(laser)
}
In touchesBegan, set the position of the sprite to the location of the touch. In this case, it's also the start of the line.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
laser.position = positionInScene
laser.setScale(1)
}
Update the sprite so that it forms a line that starts at the position of the sprite and ends at the current touch location.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let positionInScene = touch.location(in: self)
stretchLaserTo(positionInScene)
}
Stretch the sprite by setting its xScale to the distance from the start of the line to the location of the current touch and then rotate the sprite.
func stretchLaserTo(_ point: CGPoint) {
let dx = point.x - laser.position.x
let dy = point.y - laser.position.y
let length = sqrt(dx*dx + dy*dy)
let angle = atan2(dy, dx)
laser.xScale = length
laser.zRotation = angle
}
Related
I have a SKSpriteNode as a ball, it's been given all the SKPhysicsBody properties move around in all direction. What I want now is to make it unidirectional (only move in that direction it hasn't move to before and not go back in to a path it had move upon). Currently I have following thoughts on this the problem,
make a fieldBitMask, to the path that is iterated by it and repel
the ball to not go back
apply some kind of force/ impulses on the ball from touchesBegan/ touchesMoved method to keep it from going back
something that can be handled in update method
a lifesaver from stackflowoverflow, who is coding even on the weekend :)
Supporting Code snippets for better understanding,
//getting current touch position by using UIEvent methods
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchPoint = nil
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
lastTouchPoint = nil
}
//ball created
func createPlayer(){
player = SKSpriteNode(imageNamed: "player")
player.position = CGPoint(x: 220, y: 420)
player.zPosition = 1
//physics for ball
player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2)
player.physicsBody?.allowsRotation = false
player.physicsBody?.linearDamping = 0.5
player.physicsBody?.categoryBitMask = collisionTypes.player.rawValue
player.physicsBody?.contactTestBitMask = collisionTypes.finish.rawValue
player.physicsBody?.collisionBitMask = collisionTypes.wall.rawValue
addChild(player)
}
//unwarp the optional property, calclulate the postion between player touch and current ball position
override func update(_ currentTime: TimeInterval) {
guard isGameOver == false else { return }
if let lastTouchPosition = lastTouchPoint {
//this usually gives a large value (related to screen size of the device) so /100 to normalize it
let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
physicsWorld.gravity = CGVector(dx: diff.x/100, dy: diff.y/100)
}
}
Well it was a combination little hacks in touchesBegan/ touchesMoved and update func,
First you need to catch on which touch occurred, get it's name (in my
case I made nodes which had alpha of 0, but become visible upon
moving over them i.e alpha 1). In touchesBegan, touchesMoved as follow
guard let touch = touches.first else {return}
let location = touch.location(in: self)
lastTouchPoint = location
let positionInScene = touch.location(in: self)
let touchedNode = self.atPoint(positionInScene)
if let name = touchedNode.name
{
if name == "vortex"
{
touching = false
self.view!.isUserInteractionEnabled = false
print("Touched on the interacted node")
}else{
self.view!.isUserInteractionEnabled = true
touching = true
}
}
}
Second use a BOOL touching to track user interactions, on the screen by using getting a tap recogniser setup, as follow
func setupTapDetection() {
let t = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
view?.addGestureRecognizer(t)
}
#objc func tapped(_ tap: UITapGestureRecognizer) {
touching = true
}
Finally in update put checks as follow,
guard isGameOver == false else { return }
self.view!.isUserInteractionEnabled = true
if(touching ?? true){
if let lastTouchPosition = lastTouchPoint {
//this usually gives a large value (related to screen size of the device) so /100 to normalize it
let diff = CGPoint(x: lastTouchPosition.x - player.position.x, y: lastTouchPosition.y - player.position.y)
physicsWorld.gravity = CGVector(dx: diff.x/100, dy: diff.y/100)
}
}
}
I have an App that uses touchesBegan to perform an action for the user. However, sometimes touching the screen is only to leave a textField.
Is there any way to set the touchesBeagan to only start after 2 or 3 seconds while keeping the touch and if the touch is smaller than this, instead of triggering the action, the resignFirstResponder is triggered?
To help to understanding here are my touches methods:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
Feedback.share.hapticFeedback()
startPoint = nil
guard let touch = touches.first else {return}
startPoint = touch.location(in: imageView)
//Initialize whatever you need to begin showing selected rectangle below.
rectShapeLayer.path = nil
imageView.layer.addSublayer(rectShapeLayer)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, let startPoint = startPoint else {return}
let currentPoint: CGPoint
if let predicted = event?.predictedTouches(for: touch), let lastPoint = predicted.last {
currentPoint = lastPoint.location(in: imageView)
} else {
currentPoint = touch.location(in: imageView)
}
let frame = rect(from: startPoint, to: currentPoint)
//Show bounding box
rectShapeLayer.path = UIBezierPath(rect: frame).cgPath
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, let startPoint = startPoint else {return}
let currentPoint = touch.location(in: imageView)
let frame = rect(from: startPoint, to: currentPoint)
//Remove bounding box but take snapshot of selected `CGRect` by frame
rectShapeLayer.removeFromSuperlayer()
let memeImage = imageView.snapshot(rect: frame, afterScreenUpdates: true)
save(imageView: imageView, image: memeImage)
}
I found out a way to guarantee that a touch on the screen it just execute a resignFirstResponder instead of other function.
I only changed the touchesEnded(_:) method adding an "if frame.size.width < 1".
That worked well for me.
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first, let startPoint = startPoint else {return}
let currentPoint = touch.location(in: ivPhoto)
let frame = rect(from: startPoint, to: currentPoint)
rectShapeLayer.removeFromSuperlayer()
if frame.size.width < 1 {
tfTop.resignFirstResponder()
tfBottom.resignFirstResponder()
} else {
let memeImage = ivPhoto.snapshot(rect: frame, afterScreenUpdates: true)
saveCrop(cropImage: memeImage)
}
}
I would like to have the following interplay between line and ball in my game: a line gives direction and speed to the ball. The longer the line, the faster the ball.
What I have now: a ball is following the line and stops at the end of it. But it shouldn't stop here. Of course, I understand that the ball is only following the path I made. But how could I change it?
Here is my code:
import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
// Basic for dynamic sizes step01
var width = CGFloat()
var height = CGFloat()
var ball:SKSpriteNode!
var line:SKShapeNode!
var startPoint: CGPoint!
var location = CGPoint()
override func didMove(to view: SKView) {
self.backgroundColor = .purple
//declare dynamic size of the screen
width = self.frame.size.width
height = self.frame.size.height
self.physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
self.physicsWorld.gravity = CGVector.zero
createBall()
}
func createBall(){
ball = SKSpriteNode(imageNamed: "yellowBtn")
ball.position = CGPoint(x:0, y: -(height/2.5))
ball.size = CGSize(width: width/6, height: width/6)
self.addChild(ball)
}
func drawLine(endPoint:CGPoint){
if(line != nil ){ line.removeFromParent() }
startPoint = ball.position
let path = CGMutablePath()
path.move(to: startPoint)
path.addLine(to: endPoint)
line = SKShapeNode()
line.path = path
line.lineWidth = 5
line.strokeColor = UIColor.white
self.addChild(line)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if(line != nil ){ line.removeFromParent()
for touch in (touches ) {
let location = touch.location(in: self)
drawLine(endPoint: location)
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in (touches ) {
let location = touch.location(in: self)
drawLine(endPoint: location)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in (touches ) {
location = touch.location(in: self)
drawLine(endPoint: location)
}
let moveAction = SKAction.move(to: location, duration: 10)
ball.run(moveAction)
}
override func update(_ currentTime: TimeInterval) {
}
}
I have found at least a part of answer to my question: I need to calculate CGVector manually (lastPoint - firstPoint) and then apply impulse to the ball:
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in (touches ) {
location = touch.location(in: self)
drawLine(endPoint: location)
}
let dx = location.x - startPoint.x
let dy = location.y - startPoint.y
let movement = CGVector(dx: dx, dy: dy)
ball.physicsBody = SKPhysicsBody(circleOfRadius: 50)
ball.physicsBody?.applyImpulse(movement)
}
Now I should find the second part: how to set the speed of the ball accordingly to the length of the line.
everyone! First of all, I'm aware that this question is very similar to Draw images evenly spaced along a path in iOS. However, that is in Objective-C (which I can't read) and it is in a normal ViewController working with CGImageRefs. I need it in swift and using SKSpriteNodes (not CGImageRefs). Here's my issue:
I'm trying to make a program that lets the user draw a simple shape (like a circle) and places SKSpriteNodes at fixed intervals along the path drawn by the user. I've got it working fine at a slow pace, but if the user draws too quickly then the nodes get placed too far apart. Here's an example of when I draw it slowly:
User-drawn path with nodes placed approximately 60 pixels apart from each other. Blue is the start node, purple is the end node.
The goal is that each node would have a physicsBody that kept entities from crossing the line drawn by the user (those entities wouldn't be able to squeeze in between evenly spaced nodes). If the user draws too fast, however, there will be a gap in defenses that I can't fix. For example:
Note the visibly larger gap between the 7th and 8th nodes. This occurred because I drew too quickly. Many people have questions that are slightly similar but are unhelpful for my task (e.g. place a specific amount of nodes evenly spaced along a path, rather than place as many nodes as neccessary to get them 60 pixels apart along the path).
In conclusion, here is my main question again: How can I place nodes perfectly spaced along a user-drawn path of any shape? Thank you in advance for your help! Here is my GameScene.swift file:
import SpriteKit
import GameplayKit
class GameScene: SKScene {
let minDist: CGFloat = 60 //The minimum distance between one point and the next
var points: [CGPoint] = []
var circleNodes: [SKShapeNode] = []
override func didMove(to view: SKView) {
}
func getDistance (fromPoint: CGPoint, toPoint: CGPoint) -> CGFloat {
let deltaX = fromPoint.x - toPoint.x
let deltaY = fromPoint.y - toPoint.y
let deltaXSquared = deltaX*deltaX
let deltaYSquared = deltaY*deltaY
return sqrt(deltaXSquared + deltaYSquared) //Return the distance
}
func touchDown(atPoint pos : CGPoint) {
self.removeAllChildren()
//The first time the user touches, we need to place a point and mark that as the firstCircleNode
print(pos)
points.append(pos)
//allPoints.append(pos)
let firstCircleNode = SKShapeNode(circleOfRadius: 5.0)
firstCircleNode.fillColor = UIColor.blue
firstCircleNode.strokeColor = UIColor.blue
firstCircleNode.position = pos
circleNodes.append(firstCircleNode)
self.addChild(firstCircleNode)
}
func touchMoved(toPoint pos : CGPoint) {
let lastIndex = points.count - 1 //The index of the last recorded point
let distance = getDistance(fromPoint: points[lastIndex], toPoint: pos)
//vector_distance(vector_double2(Double(points[lastIndex].x), Double(points[lastIndex].y)), vector_double2(Double(pos.x), Double(pos.y))) //The distance between the user's finger and the last placed circleNode
if distance >= minDist {
points.append(pos)
//Add a box to that point
let newCircleNode = SKShapeNode(circleOfRadius: 5.0)
newCircleNode.fillColor = UIColor.red
newCircleNode.strokeColor = UIColor.red
newCircleNode.position = pos
circleNodes.append(newCircleNode)
self.addChild(newCircleNode)
}
}
func touchUp(atPoint pos : CGPoint) {
//When the user has finished drawing a circle:
circleNodes[circleNodes.count-1].fillColor = UIColor.purple //Make the last node purple
circleNodes[circleNodes.count-1].strokeColor = UIColor.purple
//Calculate the distance between the first placed node and the last placed node:
let distance = getDistance(fromPoint: points[0], toPoint: points[points.count-1])
//vector_distance(vector_double2(Double(points[0].x), Double(points[0].y)), vector_double2(Double(points[points.count - 1].x), Double(points[points.count - 1].y)))
if distance <= minDist { //If the distance is closer than the minimum distance
print("Successful circle")
} else { //If the distance is too far
print("Failed circle")
}
points = []
circleNodes = []
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
You could try resizing the vector:
func touchMoved(toPoint pos : CGPoint) {
let lastIndex = points.count - 1 //The index of the last recorded point
let distance = getDistance(fromPoint: points[lastIndex], toPoint: pos)
if distance >= minDist {
// find a new "pos" which is EXACTLY minDist distant
let vx = pos.x - points[lastIndex].x
let vy = pos.y - points[lastIndex].y
vx /= distance
vy /= distance
vx *= minDist
vy *= minDist
let newpos = CGPoint(x: vx, y:vy)
points.append(newpos)
//Add a box to that point
let newCircleNode = SKShapeNode(circleOfRadius: 5.0)
newCircleNode.fillColor = UIColor.red
newCircleNode.strokeColor = UIColor.red
newCircleNode.position = newpos // NOTE
circleNodes.append(newCircleNode)
self.addChild(newCircleNode)
}
}
It probably won't be perfect but might look better.
I've figured it out! I was inspired by Christian Cerri's suggestion so I used the following code to make what I wanted:
import SpriteKit
import GameplayKit
// MARK: - GameScene
class GameScene: SKScene {
// MARK: - Allows me to work with vectors. Derived from https://www.raywenderlich.com/145318/spritekit-swift-3-tutorial-beginners
func subtract(point: CGPoint, fromPoint: CGPoint) -> CGPoint {
return CGPoint(x: point.x - fromPoint.x, y: point.y - fromPoint.y) //Returns a the first vector minus the second
}
func add(point: CGPoint, toPoint: CGPoint) -> CGPoint {
return CGPoint(x: point.x + toPoint.x, y: point.y + toPoint.y) //Returns a the first vector minus the second
}
func multiply(point: CGPoint, by scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x * scalar, y: point.y * scalar)
}
func divide(point: CGPoint, by scalar: CGFloat) -> CGPoint {
return CGPoint(x: point.x / scalar, y: point.y / scalar)
}
func magnitude(point: CGPoint) -> CGFloat {
return sqrt(point.x*point.x + point.y*point.y)
}
func normalize(aPoint: CGPoint) -> CGPoint {
return divide(point: aPoint, by: magnitude(point: aPoint))
}
// MARK: - Properties
let minDist: CGFloat = 60
var userPath: [CGPoint] = [] //Holds the coordinates collected when the user drags their finger accross the screen
override func didMove(to view: SKView) {
}
// MARK: - Helper methods
func getDistance (fromPoint: CGPoint, toPoint: CGPoint) -> CGFloat
{
let deltaX = fromPoint.x - toPoint.x
let deltaY = fromPoint.y - toPoint.y
let deltaXSquared = deltaX*deltaX
let deltaYSquared = deltaY*deltaY
return sqrt(deltaXSquared + deltaYSquared) //Return the distance
}
func touchDown(atPoint pos : CGPoint) {
userPath = []
self.removeAllChildren()
//Get the first point the user makes
userPath.append(pos)
}
func touchMoved(toPoint pos : CGPoint) {
//Get every point the user makes as they drag their finger across the screen
userPath.append(pos)
}
func touchUp(atPoint pos : CGPoint) {
//Get the last position the user was left touching when they've completed the motion
userPath.append(pos)
//Print the entire path:
print(userPath)
print(userPath.count)
plotNodesAlongPath()
}
/**
Puts nodes equidistance from each other along the path that the user placed
*/
func plotNodesAlongPath() {
//Start at the first point
var currentPoint = userPath[0]
var circleNodePoints = [currentPoint] //Holds the points that I will then use to generate circle nodes
for i in 1..<userPath.count {
let distance = getDistance(fromPoint: currentPoint, toPoint: userPath[i]) //The distance between the point and the next
if distance >= minDist { //If userPath[i] is at least minDist pixels away
//Then we can make a vector that points from currentPoint to userPath[i]
var newNodePoint = subtract(point: userPath[i], fromPoint: currentPoint)
newNodePoint = normalize(aPoint: newNodePoint) //Normalize the vector so that we have only the direction and a magnitude of 1
newNodePoint = multiply(point: newNodePoint, by: minDist) //Stretch the vector to a length of minDist so that we now have a point for the next node to be drawn on
newNodePoint = add(point: currentPoint, toPoint: newNodePoint) //Now add the vector to the currentPoint so that we get a point in the correct position
currentPoint = newNodePoint //Update the current point. Next we want to draw a point minDist away from the new current point
circleNodePoints.append(newNodePoint) //Add the new node
}
//If distance was less than minDist, then we want to move on to the next point in line
}
generateNodesFromPoints(positions: circleNodePoints)
}
func generateNodesFromPoints(positions: [CGPoint]) {
print("generateNodesFromPoints")
for pos in positions {
let firstCircleNode = SKShapeNode(circleOfRadius: 5.0)
firstCircleNode.fillColor = UIColor.blue
firstCircleNode.strokeColor = UIColor.blue
firstCircleNode.position = pos //Put the node in the correct position
self.addChild(firstCircleNode)
}
}
// MARK: - Touch responders
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
And this results in the following:
No matter how quickly the user moves their finger, it places nodes evenly along their path. Thanks so much for your help, and I hope it helps more people in the future!
I'm trying to create an iOS game and I have it so that when the item is touched and moved it is dragged. When it is dragged the mouse is snapped to the center of the sprite. How could I make it so that this wouldn't happen?
Here is an example of what is happening.
Here are the functions dealing with touch input
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var papers = 0
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
if ((touchedNode.name?.contains("paper")) != nil) {
touchedNode.position = location
touchedNode.position.x = CGRectGetMidX(self.frame)
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
if ((touchedNode.name?.contains("paper")) != nil) {
touchedNode.position = location
touchedNode.position.x = CGRectGetMidX(self.frame)
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
if ((touchedNode.name?.contains("paper")) != nil) {
touchedNode.zPosition = 0
touchedNode.position.x = CGRectGetMidX(self.frame)
}
}
}
P.S. contains is an extension off of the String class to check if a substring is in a string
Thanks in advance!
It's fairly straightforward to drag a sprite from the touch location instead of from the center of the sprite. To do this, calculate and store the difference (i.e., offset) between the touch location and the center of the sprite. Then, in touchesMoved, set the sprite's new position to the touch location plus the offset.
You can optionally overload the + and - operators to simplify adding and subtracting CGPoints. Define this outside of the GameScene class:
func - (left:CGPoint,right:CGPoint) -> CGPoint {
return CGPoint(x: right.x-left.x, y: right.y-left.y)
}
func + (left:CGPoint,right:CGPoint) -> CGPoint {
return CGPoint(x: right.x+left.x, y: right.y+left.y)
}
In GameScene, define the following instance variable
var offset:CGPoint?
and then in touchesBegan, replace
touchedNode.position = location
with
offset = location - touchedNode.position
and in touchesMoved, replace
touchedNode.position = location
with
if let offset = self.offset {
touchedNode.position = location + offset
}
I generalized the solution to offset the sprite's position in both the x and y dimensions. In your app, you can simply offset the sprite's y position since x is ignored.
You don't need touchesBegan and touchesEnded for this. You can use just touchesMoved:
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let touchedNode = nodeAtPoint(location)
let previousPosition = touch.previousLocationInNode(self)
if (touchedNode.name == "paper") {
var translation:CGPoint = CGPoint(x: location.x - previousPosition.x , y: location.y - previousPosition.y )
touchedNode.position = CGPoint(x: touchedNode.position.x , y: touchedNode.position.y + translation.y)
}
}
The idea is to calculate translation. You can read more about this solution here. For future readers Obj-C solution on StackOverflow can be found on this link.