With how my game is actually going to play a little clearer in my mind, I had some more programming to do. I realised I would need doors, and switches to open and close them, so set about writing some very similar code to the stuff already in for “warps”.
When it came to working out collisions on these doors and door switches, I just expanded my “warp collision detector” to a general “tile collision detector” but it all went very wrong. I couldn’t figure out why collisions were not being triggered correctly: Sometimes warp tile detection would happen all the time (even when on other tiles), sometimes nothing would be detected at all, sometimes it would crash with a “nil value” error. I had to sleep on it[ref]Or go for a wee. It’s amazing how many solutions to problems I come up with when I go for a wee.[/ref].
I realised I’d only bloody initialised some of the variables used by the “make door” and “make switch” functions after calling those functions. Schoolboy error!
As I set about fixing it, I realised I had an awful lot of duplicate, or near duplicate, code. Did I really need separate functions to create warps, doors and switches? And other objects that I hadn’t implemented yet? Seemed a bit wasteful. I had the detection routines working now but it was nagging at me that I could streamline things a bit. I made the decision to scrap about a third of my code and start again.
I started by creating a generic object, er, object. Just check this beauty out:
function make_object(obsort,obspr,obn,obpairn,obx,oby,obmapx,obmapy,obframe,obticks,obticksmax,obactive) ob={} ob.sort = obsort ob.spr = obspr ob.n = obn ob.pairn = obpairn ob.x = obx ob.y = oby ob.mapx = obmapx ob.mapy = obmapy ob.frame = obframe ob.ticks = obticks ob.ticksmax = obticksmax ob.hitbox = {x=0,y=0,w=8,h=8} ob.active = obactive ob.draw = function(this) if this.ticksmax != 0 then this.ticks += 1 if this.ticks == this.ticksmax then if this.frame == 0 then this.frame = 1 else this.frame = 0 end this.ticks = 0 end end map(this.mapx+this.frame,this.mapy,this.x*8,this.y*8,1,1) end add(objects,ob) return ob end
Oh yeah. I included a function in there too. It tells the object how it is drawn on the screen, meaning I didn’t need a separate “draw things” function for each object type either. Nope, all I need to do now is:
foreach(objects, function(obj) obj:draw() end)
Lovely. I’m very pleased with it.
As you can see, I’ve done a lot with the game but it isn’t actually looking very different to how it did before. How it works, though, is much improved.
[includeme src=”https://lofi-gaming.org.uk/gamedev/frv019/freeroam.html” frameborder=”0″ width=”400″ height=”400″]
Remember you can click in that box there and actually “play” the “game”. Remember also that everything is subject to change and the terrible “graphics” are placeholders only.