random movement for random spawns with sprites

Hi I have a question. Forgive me if my problem is easy, I’m quite the beginner.

Currently i have some random spawns

[code]local enemies = {}

local enemyGroup = display.newGroup()

local enemybasicmovesheet = sprite.newSpriteSheet(“images/sprites-player.png”, 64, 32)

local enemybasicmoveset = sprite.newSpriteSet (enemybasicmovesheet, 1, 4)

sprite.add (enemybasicmoveset, “enemybasicleft”, 2, 1, 100, 0)

sprite.add (enemybasicmoveset, “enemybasicright”, 4, 1, 100, 0)

sprite.add (enemybasicmoveset, “enemybasicup”, 1, 1, 100, 0)

sprite.add (enemybasicmoveset, “enemybasicdown”, 1, 1, 100, 0)

sprite.add (enemybasicmoveset, “enemybasicidleleft”, 1, 1, 100, 0)

sprite.add (enemybasicmoveset, “enemybasicidleright”, 3, 1, 100, 0)

local spawnLimit = 0

local function spawnEnemy()

local enemy = sprite.newSprite (enemybasicmoveset)

physics.addBody(enemy, {bounce=0})

enemy.x = math.random(0, 320)

enemy.y = math.random(0, 480)

enemy.bodyType = “kinematic”

enemy.isSensor = true

enemy.index = #enemies + 1

enemyGroup:insert(enemy)

enemy.name = “enemy”

spawnLimit = spawnLimit+1
print (spawnLimit)
print (enemy.x, enemy.y)

enemies[enemy.index] = enemy

return enemy
end

while spawnLimit < 10 do spawnEnemy() end[/code]
not sure if I’m even doing it right but I would like to make each of my spawns move randomly around the screen, much like how NPCs move around randomly, sometimes staying idle.

Also how would I enable them to move accordingly with the sprite animations? (currently, as you can see in the code there aren’t many haha)

Thanks so much! [import]uid: 132505 topic_id: 23107 reply_id: 323107[/import]

the absolutely easiest way would be something like this

  
function randomMoveNPC (enemyIndex)  
  
 local theEnemy = enemies[enemyIndex]  
 local randomMovement = math.random(5) -- one for each direction +1 for stop  
  
 if randomMovement == 1 then  
 -- move up  
 theEnemy.xMove = 0 -- you need to add those   
 theEnemy.yMove = -1 -- properties on creation of enemy  
  
 elseif randomMovement == 2 then  
 -- move down  
 theEnemy.xMove = 0  
 theEnemy.yMove = 1  
  
 elseif randomMovement == 3 then  
 -- move left  
 theEnemy.xMove = -1  
 theEnemy.yMove = 0  
  
 elseif randomMovement == 4 then  
 -- move right  
 theEnemy.xMove = 1  
 theEnemy.yMove = 0  
  
 elseif randomMovement == 5 then  
 -- stop  
 theEnemy.xMove = 0  
 theEnemy.yMove = 0  
 end  
  
end  

now you need a enter frame function that iterates through all enemies and adding each xMove/yMove to their x/y coordinates. You can also change the sprite depending on NPC movement here.

hope it helps
-finefin [import]uid: 70635 topic_id: 23107 reply_id: 92413[/import]