Search code examples
luagideros

using getPosition() and setPosition() in Lua with Gideros


I am using SceneManager.: Now, the problem is I have many objects on this level, but I want only one of them to move up and down on touch, the object is taken from texture pack and is basically an animation:

If i do self:getPosition and self:setPosition, all the objects in this level change their position, how do I change position of only self.anim[frame] when the user touches the screen?

--in Play.lua

self.anim = 
{
    Bitmap.new(pack:getTextureRegion("flappy1.png", true)),
    Bitmap.new(pack:getTextureRegion("flappy2.png",true)),
}

and then something like this :

self:addChild(self.anim[1])
self:addEventListener(Event.TOUCHES_BEGIN, self.whenTouched, self)
self:addEventListener(Event.TOUCHES_END, self.whenuntouched, self)

function Play: whenTouched()
  x,y = self:getPosition()
  self:setPosition(x, y-20)
end

function Play: whenuntouched()
  x,y = self:getPosition()
  self:setPosition(x, y+20)
  print("down")
end

Solution

  • The correct way would be to create separate layer for this animation like:

    self.animationHolder = Sprite.new()
    self:addChild(self.animationHolder)
    self.anim = 
    {
       Bitmap.new(pack:getTextureRegion("flappy1.png", true)),
       Bitmap.new(pack:getTextureRegion("flappy2.png",true)),
    }
    self.animationHolder:addChild(self.anim[1])
    

    Then you would need to add/remove children from self.animationHolder to animate it (I would actually recommend using MovieClip for it, but that is another topic)

    And when you set position for self.animationHolder, only animation will move, and not all objects on scene ;)