Log In  

My question is, how do you add enemies to a game, do you use tables? Use local values in a function? Or some other way?

P#89947 2021-04-04 01:19

1

This depends on your coding style and how you're structuring your game, but basically enemies are just groups of values that you store somewhere and regularly manipulate. For example, if your game has a very small number of enemy types, you could store all the enemies of each type in a table and add some code in your update function to handle each type separately. However, if you want to handle enemies more flexibly, you could also include the function to handle an enemy within the enemy's data.

example with separate tables:

function _init()
  -- some example enemy data
  walking_enemies = {
    {x=0, y=0, dx=1, dist=0, max_dist=128}, {x=32, y=0, dx=1,dist=0,max_dist=128}
  }
  flying_enemies = {
    {x=256, y=0, dy=1, dist=0, max_dist=128}, {x=260, y=0, dy=1, dist=0, max_dist=128}
  }
end

function _update()
  -- move the enemies sideways then make them turn around at set points
  for e in all(walking_enemies) do
    e.x += e.dx
    e.dist += e.dx
    if (e.dist >= e.max_dist or e.dist <= 0) e.dx = -e.dx
  end
  -- move the enemies up or down then make them switch direction at set point
  for e in all(flying_enemies) do
    e.y += e.dy
    e.dist += e.dy
    if (e.dist >= e.max_dist or e.dist <= 0) e.dy = -e.dy
  end
end

example with one table:

function _init()
  enemies = {
    {x=0, y=0, dx=1, dist=0, max_dist=128, update=enemy_walk}, 
    {x=256, y=0, dy=1, dist=0, max_dist=128, update=enemy_fly}
  }
end

function _update()
  for e in all(enemies) do
    e.update(e)
  end
end

function enemy_walk(e)
  e.x += e.dx
  e.dist += e.dx
  if (e.dist >= e.max_dist or e.dist <= 0) e.dx = -e.dx
end

function enemy_fly(e)
  e.y += e.dy
  e.dist += e.dy
  if (e.dist >= e.max_dist or e.dist <= 0) e.dy = -e.dy
end

You would also need some check for collisions as well as code for any other mechanics your enemies have (like the ability to attack in some way), but that's more specific to the design of the enemies rather than how you add them to the game. Also, each enemy would need some way of drawing them in the _draw function, but the way to do that is almost the same as how to update them.

P#90255 2021-04-09 08:05

Nevermind I'm going to use your method with tables.

P#91664 2021-05-07 22:12

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-20 15:38:24 | 0.007s | Q:12