I’ve been a bit distracted this week, wrangling Safari extensions in Xcode, but now back to the maze. Today I wanted to get an enemy moving around on its own. Things I learned doing this:
First, you can do a test for boolean true or false – but there’s no === operator, and lots of things return true if you’re not careful. Nonetheless:
-- check for collision with wall on current path
if checkForOpenPath(mapRefX,mapRefY,v) == false then
enemyDirections[i] = chooseDirectionChange(i,v,mapRefX,mapRefY,true)
hasChanged = true
end
I also looked into the best way to iterate through tables (arrays). This seems to be:
for i, v in ipairs(enemyDirections) do
-- code here, i is index, v is value
end
And speaking of enemyDirections – I wanted to draw one enemy for now, but with the option of adding more in future, using a table of objects. That seems to work fine – I pushed an enemy object onto the table with
table.insert(enemySprites,enemySprite)
.. generating a table of enemies, and then I also defined an array of current enemy directions, enemyDirections. I can then easily iterate enemyDirections and reference the appropriate object in enemySprites:
for i, v in ipairs(enemyDirections) do
if isMultipleOf(enemySprites[i].x - topLeft,16) then
Finally, enemy logic. For now, I’m forcing the enemy to turn on collision with a wall – even if it means going backwards, if that’s the only option – and with an x% chance of turning into side paths, controlled by a random number generator:
local rng = math.random(0, 10)
if rng > 4 then
enemyDirections[i] = chooseDirectionChange(i,v,mapRefX,mapRefY,false)
end
In the “which way to turn” logic I was able to make a lot of use of the existing “checkForOpenPath” function, so that saves lots of time.
Now my second ghost bumbles happily – but aimlessly – around the maze. Next step will be to make it chase the player, and collision detection for when they meet.
Full code on Github here.