Swift Sprite Kit开始触控功能

Swift Sprite Kit Began Touch Function

我正在处理一个 xcode 项目,我试图让一个红球 SKShapeNode 在我触摸它时四处移动。我自己的源代码中touch开始class是不行的。我的代码有什么缺陷,我需要做什么才能修复它。

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

LOL 哇,这很有趣,if touchLocation == ball.position 如果你能击中球的准确像素位置,我会印象深刻。你要的是这个:

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

但就我个人而言,我会做的是 SKSpriteNode 的子 class,然后在 child 的触球例程中执行球的触球代码