Swift Sprite Kit Start Touch Function

Im messing around with the xcode project, and I'm trying to make the red SKShapeNode ball move when I touch it. My own source code in touch started the class does not do the trick. What is the flaw of my code and what do I need to do to fix it.

import SpriteKit class GameScene: SKScene { //Rectangle Skeletions var leftWallRect = CGRect(x: 0, y: 0, width: 40, height: 1000) var ball = SKShapeNode(circleOfRadius: 25); override func didMoveToView(view: SKView) { // Declare the Sprites in your scene var ball = SKShapeNode(circleOfRadius: 25); let leftWall = SKShapeNode(rect: leftWallRect); let rightWall = SKShapeNode(rect: leftWallRect); let pin = SKSpriteNode(imageNamed: "pin"); // Ball Properties ball.strokeColor = UIColor.blackColor() ball.fillColor = UIColor.redColor() ball.position = CGPointMake(self.frame.width / 2 , self.frame.height / 4 - 100 ) self.addChild(ball) // Left Wall Properties leftWall.fillColor = UIColor.purpleColor() leftWall.strokeColor = UIColor.blackColor() leftWall.position = CGPointMake(self.frame.size.width / 3 - 45, self.frame.size.height / 2 - 400) self.addChild(leftWall) //Right Wall Properties rightWall.fillColor = UIColor.purpleColor() rightWall.strokeColor = UIColor.blackColor() rightWall.position = CGPointMake(self.frame.size.width / 2 + 175, self.frame.size.height / 2 - 400) self.addChild(rightWall) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { /* Called when a touch begins */ let touch = touches.first as! UITouch let touchLocation = touch.locationInNode(self) if touchLocation == ball.position{ ball.position = touchLocation println("Touches"); } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } } 
+5
source share
1 answer

LOL wow, this is ridiculous, if touchLocation == ball.position I would be impressed if you could get to the exact location of your ball. What you want is:

 let touch = touches.first as! UITouch let touchLocation = touch.locationInNode(self) let touchedNode = self.nodeAtPoint(touchLocation) if touchedNode == ball{ ... 

But personally, what I would like to do is to subclass the SKSpriteNode class, and make my ball touch code inside this procedure for a child’s touch

+2
source

Source: https://habr.com/ru/post/1239184/


All Articles