【问题标题】:Touch implementation in game游戏中的触控实现
【发布时间】:2016-10-22 18:37:42
【问题描述】:

我正在使用带有 Xcode 8 的 Swift 3,并且我正在尝试使用 SpritKit 制作简单的游戏。基本上我想要做的是让玩家只左右移动我的精灵(在屏幕上拖动它)并在实现手指(触摸结束)后对精灵施加脉冲。我已经设法做到了,但我希望这仅在第一次触摸时发生,因此在对精灵施加脉冲后,玩家无法再与精灵交互,直到发生一些碰撞或类似情况。下面是我的代码,它不仅在第一次触摸时一直有效。

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



}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {

        let location = t.location(in: self)

        if player.contains(location)
        {
            player.position.x = location.x
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {

        if let t = touches.first {

            player.physicsBody?.isDynamic = true
            player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
        }
    }
}

【问题讨论】:

  • 您唯一需要的是一个布尔变量,无论是在场景中还是在您的某些自定义类中,它将跟踪是否允许交互。因此,在您应用冲动后,您将布尔值设置为 false,然后在 didBegin(contact:) 中相应地更改该布尔值。
  • 我可以将可变脉冲集添加为默认值,并且仅当可变脉冲大于 0 时才允许用户与精灵交互。将脉冲集脉冲设置为零后,直到开始接触发生
  • 只用真假。我的意思是 1 和 0 会起作用,但没有必要。或者,也许您可​​以使用一些physicsBody 的属性来确定是否允许交互。这实际上取决于您的游戏如何运作以及最适合您的游戏。但最重要的是,这是一项简单的任务,可以通过多种方式完成。

标签: sprite-kit swift3 game-physics xcode8 touches


【解决方案1】:

正如Whirlwind 评论的那样,您只需要一个布尔值来确定何时应该控制该对象:

/// Indicates when the object can be moved by touch
var canInteract = true

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

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {
        let location = t.location(in: self)
        if player.contains(location) && canInteract
        {
            player.position.x = location.x
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for t in touches {

        if let t = touches.first && canInteract {
            canInteract = false //Now we cant't interact anymore.
            player.physicsBody?.isDynamic = true
            player.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 50))
        }
    }
}
/* Call this when you want to be able to control it again, on didBeginContact
   after some collision, etc... */
func activateInteractivity(){
    canInteract = true
    // Set anything else you want, like position and physicsBody properties
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多