2015-12-25 11 views
5

Mi sto cazzando con un progetto xcode e sto provando a far muovere una sfera rossa SKShapeNode quando la tocco. Il mio codice sorgente al tocco ha iniziato la lezione non sta facendo il trucco. Qual è il difetto con il mio codice e cosa devo fare per sistemarlo.Kit Swift Sprite Began Touch Funzione

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 */ 
    } 
} 
+0

è '-touchesBegan: withEvent:' essere chiamato? (imposta un breakpoint per vedere se lo è) –

+0

Ho controllato e non viene chiamato. Come lo aggiusto? @NicolasMiari –

+0

In genere è perché la proprietà 'userInteractionEnabled' (ereditata da' UIResponder') è impostata su 'false'. Tuttavia, il valore predefinito è 'true' (almeno per' UIResponder', non sicuro per 'SKScene'). –

risposta

2

LOL Wow, questo è una divertente, if touchLocation == ball.position sarei impressionato se si può colpire la posizione esatta dei pixel della vostra palla. Quello che vuoi è questo:

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

Ma personalmente, quello che vorrei fare è rendere una classe secondaria di SKSpriteNode, e fare il codice tocco del tuo palla dentro tocco di questo bambino di routine

Problemi correlati