如何使用swift检测来自另一个文件的GameScene触摸

时间:2015-08-09 20:29:05

标签: swift sprite-kit touchesbegan

我目前正在使用精灵套件制作游戏。在游戏中,地面上有随机的形状和物体,您可以拾取并旋转并堆叠在一起以构建目标高度。达到目标高度后,您将进入下一级别。每个对象和形状都是在与SKNode类下的GameScene分开的swift文件中创建的。我可以使用节点中的touchesBegan,移动和结束方法来拾取对象并在屏幕上移动它。当我抓住物体时,我希望能够用屏幕上的第二根手指点击并按住屏幕旋转物体直到手指松开,所以,第一根手指抓住并按住当另一个手指旋转它时,该物体。问题是我发现SKNode几乎不可能检测到实际节点外的触摸。下面是我用于SKNode的代码。任何建议或建议将不胜感激,谢谢。

import UIKit
import SpriteKit

class GameObjects: SKNode {

    var object: SKSpriteNode
    var action: () -> Void

    init(objectImage: String, buttonAction: () -> Void ){

        object = SKSpriteNode(imageNamed: objectImage)
        action = buttonAction

        let object1Texture = SKTexture(imageNamed: "object1")
        object1Texture.filteringMode = SKTextureFilteringMode.Nearest

        let size = CGSize(width: 100, height: 100)
        object.physicsBody = SKPhysicsBody(texture: object1Texture, size: size)

        object.physicsBody?.dynamic = true
        object.physicsBody?.allowsRotation = true
        object.physicsBody?.affectedByGravity = true

        super.init()

        userInteractionEnabled = true
        addChild(object)

    }


    required init(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        for touch in (touches ) {

            let location: CGPoint = touch.locationInNode(self)

            let moveUp = SKAction.moveToY(location.y + 200, duration: 0.05)
            object.runAction( moveUp)

        }

        object.physicsBody?.dynamic = false
        object.physicsBody?.affectedByGravity = false

    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in (touches ) {

            let location: CGPoint = touch.locationInNode(self)

            object.physicsBody?.allowsRotation = true
            object.physicsBody?.dynamic = true

            object.position.x = location.x
            object.position.y = location.y + 200
        }
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

            object.physicsBody?.dynamic = true
            object.physicsBody?.affectedByGravity = true
    }

}

0 个答案:

没有答案