0

I am trying to animate random objects that are created individually on the screen at random positions, objects will be created at a random location and move towards the right and as they crosses the screen width then they will spawn from the left (beyond the screen). I am not able to understand how to animate randomly created objects on the screen. Below are the codes which i used. Please help. thanks....

--objects that are created randomly
local randoms=math.random
local randomx,randomy
local randomobjname1,randomobjname2

for i=1, 2 do
  randomx=randoms(200,400)
  randomy=randoms(600,800)
  local xlocation=randomx
  local ylocation=randomy

  local RandomObject[i]=display.newImage("object.png")
  RandomObject[i].x=xlocation
  RandomObject[i].y=ylocation

    if i==1 then
      randomobjname1=RandomObject[i]
    elseif i==2 then
      randomobjname2=RandomObject[i]
    end

  local function animateobj()
    --in this line i have confusion how to pass random x position that i got previously from the above function
    randomobjname1.x=randomx
    randomobjname2.x=randomx
    transition.to(randomobjname1,{time=1500,x=700, onComplete=animateobj})
    transition.to(randomobjname2,{time=1500,x=700, onComplete=animateobj})
  end
end
Krishna Raj Salim
  • 7,331
  • 5
  • 34
  • 66
user2588337
  • 71
  • 1
  • 12

1 Answers1

2

Are you looking for this:

local RandomObject = {}
local xPos = {}
local transitionTime = 1500

local listener2 = function( obj )
    transitionTime = 2000 -- U can select as ur need
    RandomObject[obj.tag].x = xPos[obj.tag]-400 -- U can even choose a difft. val than '400'
    animateobj(obj.tag)
end

function animateobj(i_)
    transition.to(RandomObject[i_],{time=transitionTime,x=400+xPos[i_], onComplete=listener2})
end

for i=1, 2 do
    RandomObject[i]=display.newImage("object.png")
    RandomObject[i].x = math.random(100,300)
    RandomObject[i].y = math.random(100,400)
    RandomObject[i].tag = i
    xPos[i] = RandomObject[i].x
    animateobj(i)
end

Keep Coding............ :)

Krishna Raj Salim
  • 7,331
  • 5
  • 34
  • 66
  • In the above code the objects are generated at random positions and then moving towards right, it is working perfect, but after moving the object beyond the screen to the right for the first time, the objects must spawn from the left for eg. something like x=-30,rather than generating from the same random position on the screen, how this changes can be made to this code, thanks for your help... – user2588337 Aug 08 '13 at 12:50