I’m quite new on Defold and im trying to replay the Getting started tutorial, but now using my own images assets …
right now im stuck on “STEP 3 - Make the ground moving”.
my background image has 768x384
i create a collection with 7 GO and each GO has an sprite
here is each X sprite position: 384,1152,1916,2680,3444,4208,4972
now my update Script:
for i, p in ipairs(pieces) do
local pos = go.get_position(p)
if pos.x <= -384 then
pos.x = 4972 + (pos.x + 384)
--print(pos)
end
pos.x = pos.x - self.speed
go.set_position(pos, p)
end
but when i run the project after a time there is a long space without background images…
I’m guessing your screen width is 768, like your background. Is this what you are looking for?
if pos.x <= -384 then
pos.x = pos.x + 768 * 2
end
“When the pos is half the screen to the left (-384), which means that the sprite is completely off screen, increment the x-value by two screens (2 * 768) so that it is completely off to the right, before moving it left again”
To improve the code further you should define variables for things like width etc so you don’t repeat naked constants (e.g. 768) everywhere in the code, it makes it easier if you want to change the width later on. A function could also make it easier to read.
local width = 768
local function wrap_right(pos)
if pos.x <= (-0.5 * width) then
pos.x = pos.x + width * 2
end
end
Edit: Oops, as I recall in that example, the ground-pieces are not as wide as the background, right? You need to factor in their widths as well if they are not 768. The code I posted might not work exactly as is, but should be close. Something like this?
local screen_width = 768
local piece_width = <some value>
local function wrap_right(pos)
if pos.x <= (-0.5 * piece_width) then
pos.x = pos.x + screen_width + piece_width
end
end
I think jhonatanvinicius is scrolling backgrounds instead of the ground sprite, if so, remove the
(pos.x + 384) as this is adding half a screen again to the position of 4972 which you’ve already calculated in advance that is the position to move to.
Also if each background is 768 pixels then your values should be 384,1152,1920,2688,3456,4224,4992.
Ragnar’s advice about coding is spot on, but this is something that will come with time.
(pos.x + 384) as this is adding half a screen again to the position
function update(self, dt)
for i, p in ipairs(pieces) do
local pos = go.get_position(p)
if pos.x <= -384 then
pos.x = 4992 + 384 -- + (pos.x + 384)
--print(pos)
end
pos.x = pos.x - self.speed
go.set_position(pos, p)
end
end
If you haven’t found the issue yet I can take a look. Synchronize your files and add me (bjorn.ritzl@king.com) as a team member in the Defold Dashboard.
Ah, I see what you’ve done now. You have changed the position of the sprites, not the game objects. All game objects are on 0,0 and the sprites are offset. The sprites should all be at 0,0 and you should offset the entire game objects since those are the ones that you move and check positions against.