Page 1 of 1

Function question

Posted: Tue Apr 24, 2012 8:21 pm
by brozenadenzen
Hi, this might be a noob question but I have't actually needed it until now. For my game I am doing some collision detection in combination with movement of the character. Looks something like
love.update(dt)
if key.isDown (direction) then
check coordinates
if coordinates are ok then
change playerX, playerY
But this is good for my character, I would like to make the enemies to move on the same pattern and since to make the check for each enemy in the update function is too long I though to put the above in a function and just to call it whenever I want some movement/collision detection to take place. The new function should look something like movementDirection (objectX, objectY, speed). I have attached the code for it. The problem is I haven't actulaly needed to call outer function so far, and don't know how exactly to do it. Any advice would be nice.

Re: Function question

Posted: Tue Apr 24, 2012 8:44 pm
by brozenadenzen
So my actualy question after all the things above is - how do you build a function and call it to love.update(dt), I mean how you build the arguments etc so the program will know which thing is which.

Re: Function question

Posted: Wed Apr 25, 2012 12:20 am
by veethree
to make a function somewhere in the lua file do something like this:

Code: Select all

function myfunction(arg1, arg2, arg3)
	--function stuff
end
The arguments are basically like local variables. You can use them in the function..Here's a simple function that adds 2 numbers together and returns the outcome

Code: Select all

function AddNumbers(num1, num2)
	return num1 + num2
end
Here's a simple program demonstrating it's usage:

Code: Select all

function love.load()
	num = 0
end

function love.draw()
	love.graphics.print(num, 10, 10)
end

function love.keypressed(key)
	if key == "q" then
		num = AddNumbers(5, 8)
	end
end

function AddNumbers(num1, num2)
	return num1 + num2
end
This should give you an idea on how functions work.

But for what you're doing you don't necessarily need functions..you can just have a boolean that is false by default, and when you want some collision or movement to happen you set it to true. then in love.update you do something like
if boolean then (This checks if the boolean is set to true.)
--the code you wanted in the function
end

That way when the boolean is set to false the engine will skip that part of love.update.

Also in case you didn't know a boolean is a variable that can either be true or false.

Hope this helps.

Re: Function question

Posted: Wed Apr 25, 2012 5:02 pm
by brozenadenzen
10x man, this really helped :D