Re: Stuck with local variables
Posted: Tue Dec 31, 2013 3:32 pm
Yes. Nothing is ever copied in Lua unless you do it yourself, it's all object references.
Code: Select all
function spawnBullet( player )
bullet = {
owner = player
-- behaviour code and the like also goes here
}
end
Code: Select all
-- this one is semi-global because it's a very high-level object
local collision = require 'collision'
collision.register( bullet )
function collision.register( obj )
table.insert( self.registered, obj )
end
-- every frame, you call this function to update the collision handler and handle the collisions
collision.update = function()
-- handle collisions by iterating over all known objects and checking them for collisions with each other object... left as an excercise to the reader
-- assume we have a current object we're checking collision with, and a target that we know overlaps the current object
if( current.collidesWith( target ) then
current.handleCollisionWith( target )
end
end
Code: Select all
function bullet.collidesWith( target )
-- if you want the bullet to ignore the collision, you can return false. for example, indestructible enemies could have this property set
if not target.hittable then
return false
end
-- remember how we set the player when we created the bullet? I explain why we're checking against factionID below.
if self.owner.factionID ~= target.factionID then
return true
end
end
function bullet.handleCollisionWith( target )
-- whatever you like... lets just reduce HP or something
target.hp = target.hp - 1
-- you could also use a function like target.takeDamage( 1 ), that would let you handle death logic, impact animations, etc on the target.
end
Code: Select all
-- spawning a new bullet but passing an enemy as the owner
spawnBullet( enemy )