2015-02-10 74 views
1

我希望能够用手指移动精灵。我首先有一个可变的手指是否在子画面或不:如何用手指移动精灵?

var isFingerOnGlow = false 

然后我有touchesBegan函数其中I改变上述变量的值如果用户触摸精灵:

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

    if let body = physicsWorld.bodyAtPoint(touchLocation) { 
     if body.node!.name == GlowCategoryName { 
      println("Began touch on hero") 
      isFingerOnGlow = true 
     } 
    } 
} 

有时候它可以工作,控制台显示“开始接触英雄”,有时不会。有没有更好的方法来编码第一部分?

那么我想知道如果我touchesMoved下面的代码是有效的:

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { 
    if isFingerOnGlow{ 
     var touch = touches.anyObject() as UITouch! 
     var touchLocation = touch.locationInNode(self) 
     var previousLocation = touch.previousLocationInNode(self) 

     var glow = SKSpriteNode(imageNamed: GlowCategoryName) 

     // Calculate new position along x for glow 
     var glowX = glow.position.x + (touchLocation.x - previousLocation.x) 
     var glowY = glow.position.y + (touchLocation.y - previousLocation.y) 

     // Limit x so that glow won't leave screen to left or right 
     glowX = max(glowX, glow.size.width/2) 
     glowX = min(glowX, size.width - glow.size.width/2) 

     glow.position = CGPointMake(glowX, glowY) 
    } 
} 

...

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 
    isFingerOnGlow = false 
} 
+0

发光应该做什么?在'touchesMoved'中? – rakeshbs 2015-02-10 17:20:52

+0

获取应该移动的节点。我在http://www.raywenderlich.com/84341/create-breakout-game-sprite-kit-swift上找到了代码,然后对其进行了一些修改。但它有时只是起作用。 – ecoguy 2015-02-10 17:24:52

回答

2

您可以修改这样的功能来跟踪触摸。

var isFingerOnGlow = false 
var touchedGlowNode : SKNode! 


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

    let body = self.nodeAtPoint(touchLocation) 
    if body.name == GlowCategoryName { 
     println("Began touch on hero") 
     touchedGlowNode = body 
     isFingerOnGlow = true 
    } 

} 

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { 

    if isFingerOnGlow{ 

     let touch = touches.anyObject() as UITouch! 
     let touchLocation = touch.locationInNode(self) 
     let previousLocation = touch.previousLocationInNode(self) 
     let distanceX = touchLocation.x - previousLocation.x 
     let distanceY = touchLocation.y - previousLocation.y 

     touchedGlowNode.position = CGPointMake(touchedGlowNode.position.x + distanceX, 
      touchedGlowNode.position.y + distanceY) 
    } 
} 

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { 
    isFingerOnGlow = false 
}