How to pass parent sprite parameters into child's update function

If I have enemies and I create Shadows for each of them, is there a way I can pass a continuous positioning of the enemy?

I know I can initiate the Shadow with something like self.shadow = Shadows(self.x,self.y) and then include self.shadow:moveTo(self.x-5, self.y+20) in the parent object update, but if I have to do further calculations, how would I pass the parent parameters into the Shadow:update?

In other words, in my Shadows:update function, I currently have a global variable of PLAYER_X. However, I want to use self.x from the parent object for any object. Thanks!

class('Shadows').extends(AnimatedSprite)

function Shadows:init(x,y)
	self.shadowsSprite = gfx.imagetable.new("images/shadows")
	Shadows.super.init(self, self.shadowsSprite)
	self:moveTo(x, y)
	self:playAnimation()
end

function Shadows:update()
  self.shadowFrame = math.floor(((PLAYER_X-moonPosX)/#self.shadowsSprite)+(#self.shadowsSprite/2))
end

I'm not completely clear on your scenario, is the problem knowing the parent or getting information from the parent?

knowing the parent
You could pass a reference to the parent to the child object as an init parameter.
Shadows:init(x, y, parent)

getting info from the parent
theparentobj.x
or write getter/setter functions on the parent object class

1 Like

That's super helpful! However, not sure I'm doing it correctly.

I can called a child through the parent with: self.shadow = Shadows(self.x,self.y,self) then I added the "parent" into function Shadows:init(x,y, parent) as you pointed out. This allows me to print the parent table print(parent) or even positioning `print(parent.x)' in the init function (this is great, but can also do this with x and y for positioning in the init). However, in the child update, I get nil when trying to print the same (below).

function Shadows:update()
	print(parent.x)
end

Error: shadows.lua:22: attempt to index a nil value (global 'parent')

Would I have to make the parent objects global and just grab it's positioning with something like theparentobj.x?

Shouldn't you call self.parent.x instead of parent.x ?

function Shadows:update()
	print(self.parent.x)
end
2 Likes

Thanks!

You are correct. If I include self.parent = parent in the init function, then I can use self.parent.x. Appreciate it!

2 Likes

Glad you got to a suitable solution!

1 Like

Thanks Matt for your help and thanks Daeke for adding onto it!

1 Like