【问题标题】:Move sprite forever永远移动精灵
【发布时间】:2016-08-03 16:35:49
【问题描述】:

当我按下屏幕上的按钮时,我试图将精灵向右移动。但是,当我尝试这样做时,我只有将精灵移动到某个点的解决方案。所以...我希望精灵永远向右移动,或者直到我做其他事情。

这是在 Xcode 中使用 SpriteKit 中的 Swift。

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

    for touch : AnyObject in touches{

        let pointInTouch = touch.locationInNode(self)
        let tappedNode = nodeAtPoint(pointInTouch)
        let tappeNodeName = tappedNode.name

        if tappeNodeName == "Btn"{

            player.physicsBody?.velocity = CGVectorMake(0, 0)

            let action = SKAction.applyImpulse(CGVectorMake(400, 0), duration: 1)
            player.runAction(SKAction.repeatActionForever(action))

            print("Touched!")                
        }
    }
}

【问题讨论】:

  • 你想永远向右移动精灵,但是当它退出场景并且不再可见时会发生什么?

标签: swift xcode sprite-kit


【解决方案1】:

您可以简单地将节点向右移动,直到它确实存在于场景中

class GameScene: SKScene {

    private var player: SKSpriteNode!

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

        guard let touch = touches.first else { return }
        let pointInTouch = touch.locationInNode(self)
        let tappedNode = nodeAtPoint(pointInTouch)
        if tappedNode.name == "Btn"{
            let moveToRight = SKAction.moveToX(self.frame.width + player.frame.width, duration: 5)
            player.runAction(moveToRight)
        }

    }
}

更新:恒速

如果您希望玩家以恒定速度移动,您可以使用此代码。

如您所见,我正在使用space / speed 计算持续时间。您只需要为您的场景找到最佳的速度常数值。

class GameScene: SKScene {

    private var player: SKSpriteNode!

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

        guard let touch = touches.first else { return }
        let pointInTouch = touch.locationInNode(self)
        let tappedNode = nodeAtPoint(pointInTouch)


        let deltaX = self.frame.width + player.frame.width - player.position.x
        let speed: CGFloat = 10 // <-- change this to find the best value for you
        let duration: NSTimeInterval = NSTimeInterval(deltaX / speed)

        if tappedNode.name == "Btn"{
            let moveToRight = SKAction.moveByX(deltaX, y:0, duration: duration)
            player.runAction(moveToRight)
        }

    }
}

【讨论】:

  • 嗨,伙计,只是好奇,我经常看到守卫在 touchesBegan 中让 touch ,但仔细想想,如果 touchesBegan 被解雇,touches 必须至少有第一个元素,否则我忘记了什么?这可能对其他触摸方法有意义..
  • @AlessandroOrnano:我同意,我从未发现 touches 设置为空。我使用guard 只是因为我喜欢它,但我认为在这里强制展开可以被认为是安全的。
  • @appzYourLife 感谢您的帮助!还有一个问题。如果你想以恒定的速度移动精灵。因此,即使将精灵放在屏幕的左侧或中间,精灵也会以相同的速度向屏幕右侧运行。
  • @appzYourLife 太棒了!非常感谢您的帮助:)
  • 唯一的问题是您现在失去了原始代码所具有的多点触控功能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 2023-03-15
  • 2017-05-19
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多