Hi,
I’m just starting so I’m still trying to get a good understanding of the basics.
here is a simplified version of what I am trying to do : basically adding a number of balls to the screen and move them.
My questions are contained in the code and will be easier to understand in the context.
Any pointer is greatly appreciated
Code
main.lua
[lua]require (“Balls”)
require (“Ball”)
local Game = {}
function Game:startSetup()
local Balls = Balls:new()
Balls:setup()
end
Game:startSetup()
Balls:animate()
– How can I change the position of an instance of my Ball class?
– I would like to move my objects (circles) independantly
– -> …[/lua]
balls.lua
[lua]Balls = {}
Balls_mt = {__index = Balls}
function Balls:new()
local new_inst = {}
setmetatable(new_inst, Balls_mt)
return new_inst
end
– SETUP
function Balls:setup()
– Set Balls Defaults
local params = {
{ radius=20, xdir=1, ydir=1, xspeed=2.8, yspeed=6.1, r=255, g=0, b=0, posx=400, posy=150 },
{ radius=50, xdir=-1, ydir=-1, xspeed=1.8, yspeed=1.5, r=115, g=23, b=33, posx=200, posy=200 }
}
for i, j in pairs(params) do
ball = Ball:new(j)
end
end
– ANIMATE
function Balls:animate()
local _Balls=self
– Question : How to access .move method for each instance of the Ball class?
for i, ball in pairs(_Balls) do
ball:move() – Doesn’t work | Error : attempt to index local ‘ball’ (a function value)
end
end
return Balls[/lua]
ball.lua
[lua]Ball = {}
Ball_mt = {__index = Ball}
function Ball:new(params)
local new_inst = {}
setmetatable(new_inst, Ball_mt)
– Default Location
local default_xpos = display.contentWidth*0.5
local default_ypos = display.contentHeight*0.5
– Draw Ball
local new_inst = display.newCircle(default_xpos, default_ypos, params.radius )
new_inst.x = params.posx
new_inst.y = params.posy
– Copy params to new_inst
for i, j in pairs(params) do
new_inst[i] = j
end
return new_inst
end
– I need to access that function from main.lua and balls.lua
function Ball:move()
print (“Move Ball”)
end
return Ball[/lua]
My questions
- I believe that if I understand how to access methods for instances of a class I will be able to make progress
- Is there a table that stores all the instances of a class?
Thank you [import]uid: 95346 topic_id: 20854 reply_id: 320854[/import]