使用Corona SDK实现背景无限滚动。

我正在尝试在 corona sdk 中滚动一个背景(无限背景)

我使用了两个重复的图像(854x176)。

我尝试了这个函数:

function mov(self, event)
    if self.x < -854 then
        self.x = 854
    else
        self.x = self.x - self.speed
    end
end

它工作得很好,但是问题在于重复之间出现了一个小白色空间。 有更好的方法来做这件事吗?

点赞
用户2964945
用户2964945

一种方法是利用Graphics 2.0 Engine的特性,称为repeating fills。

以下是具体步骤:

  1. 设置默认的纹理包围模式为x(你也可以对y做同样的操作):
display.setDefault("textureWrapX", "mirroredRepeat")

包围的模式有:

  • "clampToEdge"(默认)-截止填充不会重复。
  • "repeat" -填充会重复,就像同样的图瓦被放置在一起。
  • "mirroredRepeat"-填充以镜像的方式重复,每个图瓦都是相邻的镜像。
  1. 创建一个大小为你想要的背景的矩形,例如全屏幕。
local background = display.newRect(display.contentCenterX, display.contentCenterY, 320, 480)
  1. 使用你的背景图像来填充你的显示对象。
background.fill = {type = "image", filename = "background.jpg"}
  1. 使用适合你的应用程序的任何方法来使其动画。下面只是一种方式:
local function animateBackground()
    transition.to(background.fill, {time=5000, x=1, delta=true, onComplete=animateBackground})
end

animateBackground()

在这里,你只是在background填充对象的x属性上运行了过渡,delta=true表示我们更多地使用x值的变化而不是最终结束值(请参见此处)。

调整时间、x的值,将delta设为false、试验包围模式,以了解它对动画的影响。你甚至可能意外地发现一些很酷的效果,以后可能会想要使用......

查看Brent Sorrentino的这篇优秀的教程,他对填充进行了更详细的说明。此外,在Graphics-Premium/PatternFill下查看CoronaSDK中的示例代码。

全部代码:

display.setDefault("textureWrapX", "mirroredRepeat")

local background = display.newRect(display.contentCenterX, display.contentCenterY, 320, 480)
background.fill = {type = "image", filename = "background.jpg" }

local function animateBackground()
    transition.to( background.fill, { time=5000, x=1, delta=true, onComplete=animateBackground } )
end

animateBackground()
2014-11-14 10:57:11