swift / spritekit移动然后触摸元素

时间:2017-05-24 05:58:06

标签: ios swift sprite-kit uitouch

我目前正在使用spritekit快速开发游戏。我的操纵杆使用this库工作,这一切都很好。我还将操纵杆移动到用户使用此代码点击的位置:

func updateJoystickPosition(pos: CGPoint) {
    let posX = -(self.sceneSize.width/2) + pos.x
    let posY = (self.sceneSize.height/2) - pos.y
    let newJoystickPos = CGPoint(x: posX, y: posY);

    self.joystick.position = newJoystickPos
}

也可以正常工作,然而,操纵杆不会使用那个水龙头。你必须点击操纵杆的实际操纵杆节点,所以很明显,我希望用户将手指放在屏幕上并立即开始移动它以移动播放器。

操纵杆自动开始跟踪此功能

open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print(touches)

    if let touch = touches.first, stick == atPoint(touch.location(in: self)) {
        tracking = true
        startHandler?()
    }
}

问题:无论如何,我是否可以修改touchesBegan功能或任何其他功能以达到预期效果?

1 个答案:

答案 0 :(得分:1)

您必须覆盖touchesMoved(_ touches: ,with event:),并且在此方法中只处理所有touches

例如:

var startTouchingPoint = CGPoint.zero // property

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
       startTouchingPoint = touch.location(in: self.camera!))
       yourControllerPlace.position = startTouchingPoint
       stickOnYourJoystick.position = CGPoint.zero
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches { 
       let point = touch.location(in: self.camera!))
       let convertedPoint = CGPoint(x: point.x - startTouchingPoint.x,
                                    y: point.y - startTouchingPoint.y)

       stickOnYourJoystick.position = convertedPoint

    }
}