1

I was learning about SKNodes in Swift and have encountered a problem. App was supposed to be very simple: touching screen and getting node to appear in the touched position. I don't know why but the rectangle keeps showing in different place on the screen but sn.position is the same as touch.location(in: view) position. What's wrong?

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    private var spinnyNode : SKShapeNode?
    private var touchPoint : CGPoint!

    override func didMove(to view: SKView) {

        let size = CGSize(width: 50, height: 50)

        spinnyNode = SKShapeNode(rectOf: size, cornerRadius: CGFloat(0.6)) //init

        if let spinnyNode = self.spinnyNode{

            spinnyNode.lineWidth = 3

            let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1))
            let fade = SKAction.fadeOut(withDuration: 0.5)
            let remove = SKAction.removeFromParent()

            spinnyNode.run(rotate)
            spinnyNode.run(SKAction.sequence([fade, remove]))

        }
    }

    func touchDown(point pos : CGPoint){
        if let sn = self.spinnyNode?.copy() as! SKShapeNode? {

            sn.position = CGPoint(x: touchPoint.x , y: touchPoint.y)
            print("touchDown x:\(touchPoint.x), y:\(touchPoint.y)")

            self.addChild(sn)
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard touches.count == 1 else{
            return
        }
        if let touch = touches.first{
            touchPoint = touch.location(in: view)

            touchDown(point: touchPoint)
            print("touchesBegan -> x: \(touchPoint.x) y: \(touchPoint.y)")
        }
    }
mikro098
  • 2,173
  • 2
  • 32
  • 48

1 Answers1

0

Try doing something like this

import SpriteKit
import GameplayKit

class GameScene: SKScene {

//use whichever image for your node
var ballNode = SKSpriteNode(imageNamed: "ball")

var fingerLocation = CGPoint()

override func didMove(to view: SKView) {

    ballNode.size = CGSize(width: 100, height: 100)
    ballNode.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.5)

}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesBegan(touches, with: event)


    if let location = touches.first?.location(in: self){

        if let copy = ballNode.copy() as? SKSpriteNode {
            copy.position = location
            addChild(copy)
        }
    }
}

}

Every time I click on a random spot, the ball appears. Hope this helps.

sicvayne
  • 620
  • 1
  • 4
  • 15
  • When i try this my touched location and skspritenode postion set in differnt location. for example. when i touch point is(10,-20) the skspritenode locate different position. when i click on that sksprite node that position is different. how to slove that. my need is when i click on sigle position sksprite node locate on that point – Araf Jul 04 '17 at 11:56