【问题标题】:How to remove an impulse with numerous touches (SpriteKit)如何消除多次触摸的冲动(SpriteKit)
【发布时间】:2017-12-30 04:53:33
【问题描述】:

我控制了游戏,当你触摸时,角色飞向左侧,第二次触摸时角色飞向右侧,但是当角色在飞行中并且我多次触摸时,角色抛出在不同的方向,他飞起来,如何解决它

我希望玩家在飞行时不产生冲动

enum BodyType: UInt32 {
     case playerr = 1
     case walll = 2
}

var direction: Direction?
var isInFlight = true    






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

 if isInFlight == true {
        return

    } else  {


    player?.removeAllActions()

    switch direction  {
    case .left:
        player?.run(SKAction.moveBy(x: 700, y: 0, duration: 1))
        player?.physicsBody?.applyImpulse(CGVector(dx: 700, dy: 500))

        direction = .right
    case .right:
        player?.run(SKAction.moveBy(x: -700, y: 0, duration: 1))
        player?.physicsBody?.applyImpulse(CGVector(dx: -700, dy: 
 500))

        direction     

 }

 }



 func didBegin(_ contact: SKPhysicsContact) {

    let firstBody: SKPhysicsBody
    let secondBody: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if ( firstBody.categoryBitMask == BodyType.playerr.rawValue && secondBody.categoryBitMask == BodyType.walll.rawValue) {

        print("Add")
        isInFlight = false 

    }

}


func didEnd(_ contact: SKPhysicsContact) {

    let firstBody: SKPhysicsBody
    let secondBody: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if (firstBody.categoryBitMask == BodyType.playerr.rawValue && secondBody.categoryBitMask == BodyType.walll.rawValue) {
        print("End")
        isInFlight = true 

    }
}

【问题讨论】:

  • 1) 永远不要使用图像来共享代码,SO 旨在将代码格式化以便人们可以使用它。 2)你正在做动作和物理,这真的让两个引擎都搞砸了。二选一

标签: ios swift sprite-kit touchesbegan


【解决方案1】:

不确定你想用你的应用程序完成什么,但这就是我使用touchesBegantouchesEndedisInFlight bool 设置为true/false 的意思。非常简单的概念,但您在应用逻辑中实现它的方式取决于您。

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

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        isInFlight = true
    }

【讨论】:

  • 我给播放器加了一个冲动,但这并没有解决问题
  • 在这种情况下,我认为问题一定出在代码的其他地方。如果您有 Github 帐户,也许您可​​以在示例项目中复制问题并在 Github 上共享完整代码。这将使人们更容易发现问题。
  • 我更新了这个问题。抬头看,可能更清楚我要做什么
  • 如果您不希望玩家在飞行中时冲动发挥作用,请在玩家飞行时设置类似isInFlight = true 的布尔值。然后检查 touchesBegan 方法中的布尔值,如果布尔值为真,则不要添加脉冲,即 if isInFlight == true { return } else { // add the impulse like you are doing }。当玩家不再飞行时不要忘记设置isInFlight = false
  • 我不明白在哪里设置 (isInFlight = false)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
相关资源
最近更新 更多