This is a little class I made today, I am wondering if anyone has any suggestions to streamline, etc. Also Lua is new to me and I am having trouble passing vectors to functions and using them in the functions. Any explanation on that would also be welcomed. And lastly a huge thank you to this forum, the wiki, and David Such’s tutorial for helping me get going!
Here is the Main “Class” (Are we calling them classes?)
function setup()
pColor = color(67, 132, 128, 255)
paddle = Paddle(WIDTH/2,5,80,15,pColor)
watch("Gravity.x")
watch("Gravity.y")
end
-- This function gets called once every frame
function draw()
background(0, 0, 0, 255)
rect(WIDTH/2,HEIGHT - 20, 80,15)
drawPaddle()
end
function drawPaddle()
paddle:draw()
end
And here is the Paddle class
Paddle = class()
-- Josh Knox
-- 01/01/13
--
-- This is a paddle class that moves based on gravity.
-- I would like to hear any suggestions as to the 'elegence' of the code.
--
-- I wanted to pass in posx and posy as position (vec2) but kept getting an nil error?
-- And self.pos.x doesn't seem to work
-- Anyone know why or how to pass in vector properly?
function Paddle:init(posx,posy,pWidth,pHeight,pColor)
self.pWidth = pWidth
self.pHeight = pHeight
self.posx = posx
self.posy = posy
pos = vec2(posx,posy)
size = vec2(pWidth,pHeight)
self.pColor = pColor
end
function Paddle:draw()
checkGrav()
fill(pColor)
-- I really don't like having some of the varables self.blah or others not.
rect(pos.x,pos.y,self.pWidth,self.pHeight)
end
-- It just feels like there are alot of 'if's in this function...any ideas?
function checkGrav()
-- This function checks boundaries first to avoid 'bouncing' on the edges
if pos.x >= 0 and pos.x <= WIDTH - size.x then
if Gravity.x > 0 then
pos.x = pos.x + (20 * Gravity.x)
end
if Gravity.x < 0 then
pos.x = pos.x - (-20 * Gravity.x)
end
end
if pos.x < 0 then
pos.x = 0
end
if pos.x > WIDTH - size.x then
pos.x = WIDTH - size.x
end
end
function Paddle:touched(touch)
-- Codea does not automatically call this method
end