【问题标题】:Repeating the background when touches began in Spritkit在 Spritekit 中开始触摸时重复背景
【发布时间】:2017-12-20 15:22:49
【问题描述】:

我有一个使用 Spritekit 永远重复背景的简单代码,我希望背景在任何触摸发生之前保持静止,并且只有在任何触摸开始时才开始动画或滚动

    *// animate the background*

    let background = SKTexture(imageNamed: "bg.png")

    let moveTheBackground = SKAction.move(by: CGVector(dx: -
    background.size().width, dy:0),  duration: 10)

    let backgroundToOriginalPosition = SKAction.move(by: CGVector(dx: 
    background.size().width, dy: 0), duration: 0)

    let animateTheBackground = 
    SKAction.repeatForever(SKAction.sequence([moveTheBackground, 
    backgroundToOriginalPosition]))


    *// loop the background animation*

    var i:CGFloat = 0
    while i < 2 {

        bg = SKSpriteNode(texture: background)
        bg.position = CGPoint(x: background.size().width * i, y: self.frame.midY)
        bg.size.height = self.frame.height
        bg.zPosition = -1
        bg.run(animateTheBackground)
        self.addChild(bg)

        i += 1
    }

我希望在 SpriteKit 中开始触摸时发生此代码, 任何帮助将不胜感激

【问题讨论】:

    标签: swift background sprite-kit horizontal-scrolling touchesbegan


    【解决方案1】:

    在任何游戏编程中,显示​​水平滚动的理想方式是使用 2 张背景图像并在水平方向上一张接一张地添加。移动两者,并且每当 background1 越过最左边的 0(从右到左滚动)将其位置更改为宽度为 x 时。使用主游戏循环来增加两个背景位置。在您的情况下,使用一个名为 allowScroll 的标志,在 touchesBegin 时将其设置为 true。如果 allowScroll 设置为 true,则在游戏循环中增加/减少背景图像位置。

    【讨论】:

    • 非常感谢大师,可以说我得到了上面的代码,它很简单,它的工作全部完成我希望它在 touchesbegan 方法中运行,所以当有人触摸屏幕时,背景开始从右到在任何触摸发生之前离开,背景应该是静止的,没有移动,当屏幕触摸背景应该开始移动时,我怎样才能做到这一点?谢谢
    • @mue,您正在回答您自己的问题。将运行代码放入您的触摸开始事件中
    • Knight0fDragon,我已经做到了,通过将代码放在 touchesBegan 方法中,背景消失,因为它在 didMove(查看:SKView)函数上不再可用,我想要的是游戏加载时可用的背景和当我触摸屏幕时,背景应该无限地向左移动
    • @mue,在 init 方法中将背景图像作为子元素添加到 self,并在 touchesBegin 方法中运行操作。确保您将背景实例设置为类成员。
    【解决方案2】:

    将移动代码放在 touchesMoved 函数中,以使背景与触摸对应地移动

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多