0
\$\begingroup\$

I have this code to spawn a simple enemy outside the window:

local function spawnGrupo1()
  local color01 = display.newImage("assets/img/enemigos/blue.png")
  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

But I want to be able to spawn multiple enemies from that point, and I can't figure it out.

I tried this, but it doesn't work:

local function spawnGrupo1()
  local numero = math.random(1, 3)

  if numero == 1 then
    local color01 = display.newImage("assets/img/enemigos/blue.png")
  end
  if numero == 2 then
    local color01 = display.newImage("assets/img/enemigos/yellow.png")
  end
  if numero == 3 then
    local color01 = display.newImage("assets/img/enemigos/red.png")
  end
  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

How can I approach the problem?

\$\endgroup\$
  • \$\begingroup\$ Can't you take local color01 out of the scope of the ifs? E.g. by declaring it just after local numero ? \$\endgroup\$ – Vaillancourt Jun 8 '16 at 19:07
  • \$\begingroup\$ You probably should tell how or why 'it does not work'... \$\endgroup\$ – Vaillancourt Jun 8 '16 at 19:42
0
\$\begingroup\$

I'm assuming you have issues with the scope of the variable since you simply say 'It doesn't work'.

I'm not familiar with Lua, but I'd go with something like this:

local function spawnGrupo1()
  local numero = math.random(1, 3)
  local color01

  if numero == 1 then
    color01 = display.newImage("assets/img/enemigos/blue.png")
  end
  if numero == 2 then
    color01 = display.newImage("assets/img/enemigos/yellow.png")
  end
  if numero == 3 then
    color01 = display.newImage("assets/img/enemigos/red.png")
  end

  color01.x = 40
  color01.y = -50
  physics.addBody( color01,{density = 5.0, friction = 0.0, bounce = 0} )
end

timer.performWithDelay( 1000, spawnGrupo1, 0)

In your implementation, each color01 is local the the if bloc. By declaring it outside of the if blocs like it's been done above, you make sure that it is the same variable that will be used in the addBody function call.

You can read a bit more about the concept of scope in lua here.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.