elpita
elpita

Reputation: 1115

Trying to change an object position on touch using spritekit and swift

So I have this code as part of a scene:

import SpriteKit

class GameScene: SKScene {

    override func didMoveToView(view: SKView) {

        // set the background color
        backgroundColor = SKColor.whiteColor()

        var Player = SKShapeNode(circleOfRadius: 20)
        Player.position = CGPoint(x: size.width/2, y: size.height/2)
        Player.name = "player"
        Player.fillColor = SKColor.blackColor()
        Player.physicsBody = SKPhysicsBody(circleOfRadius: 20)
        Player.physicsBody?.dynamic = false
        addChild(Player)

    }

        // touch
        override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

            let touch = touches.anyObject() as UITouch
            let touchLocation = touch.locationInNode(self)

            Player.position = CGPoint(x: size.width*0.2, y: size.height*0.2)
            print("you touched")

    }
}

I get an error saying

"use of unresolved identifier "Player"

I'm guessing since the player was first created in didMoveToView function it doesn't recognize "Player" in the touchesBegan function. How can I fix this issue? All i want to do is make the object to that position when you touch the screen anywhere.

Upvotes: 1

Views: 755

Answers (1)

Mr. Developer
Mr. Developer

Reputation: 3417

try this

var Player = SKShapeNode(circleOfRadius: 20)

...

override func didMoveToView(view: SKView) {
    Player.name = "player"
    Player.fillColor = SKColor.blackColor()
    Player.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    Player.physicsBody?.dynamic = false
    addChild(self.Player)
}

override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
    let touch = touches.anyObject() as UITouch
    let touchLocation = touch.locationInNode(self)

    self.Player.position = touchLocation.position

}

Upvotes: 2

Related Questions