【问题标题】:How would I move my node up when there is a touch and hold on the screen in Swift Spritekit?当在 Swift Spritekit 中触摸并按住屏幕时,我将如何向上移动我的节点?
【发布时间】:2015-04-23 16:19:33
【问题描述】:

当用户触摸屏幕并按住它时,我希望SKSpriteNode 飞起来,当用户停止触摸后,它又会掉到地上。现在我正在使用敲击将节点向上移动并在 touchesEnded 中将重力设置为 false 以使其落到地上。我将如何让它发挥作用。谢谢!

   var touchingScreen = false

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesBegan(touches, withEvent: event)
    touchingScreen = true
}


    override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    super.touchesCancelled(touches, withEvent: event)
    touchingScreen = false
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    super.touchesEnded(touches, withEvent: event)
    touchingScreen = false
}

 override func update(currentTime: CFTimeInterval) {
    if touchingScreen {
        // Adjust the CGVector to suit your needs.
        heroNode.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 10))


    }
}

【问题讨论】:

    标签: xcode swift touchesbegan


    【解决方案1】:

    首先,您需要跟踪用户何时触摸并按住屏幕。你可以这样做,在你的SKScene:

    var touchingScreen = false
    
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
        super.touchesBegan(touches, withEvent: event)
        touchingScreen = true
    }
    
    override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
        super.touchesCancelled(touches, withEvent: event)
        touchingScreen = false
    }
    
    override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
        super.touchesEnded(touches, withEvent: event)
        touchingScreen = false
    }
    

    其次,您现在需要在用户按下屏幕时让对象向上移动,再次在您的SKScene 中:

    override func update(currentTime: CFTimeInterval) {
        if touchingScreen {
            // Adjust the CGVector to suit your needs.
            sprite.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 50))
        }
    }
    

    或者,如果您希望对象以恒定速度向上移动,请替换:

    sprite.physicsBody!.applyImpulse(CGVector(dx: 0, dy: 50))
    

    sprite.physicsBody!.velocity = CGVector(dx: yourDx, dy: yourDy)
    

    希望有帮助!

    【讨论】:

    • 谢谢,我回家试试看!
    • 它直接向上,当我放手时它不会再向下。
    • 您需要确定heroNode.physicsBody?.affectedByGravity = true,这可能是问题所在?
    • 可以,但是触摸并按住不起作用。它只响应点击。
    • 当我放开屏幕时它也不会回落,它只是继续向上。我在 touchesEnded 中设置了 affectedByGravity 为 true。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多