Log In  


When I try to run the code listed below, my game freezes because of the while loop. Can anyone shed some light on how I can prevent the while loop in this code snippet from choking? Or if there's a better way all together?

I'm hoping to add additional objects to these functions (though they would be single objects instead of sets of 30 and 15, but I'm not at all an experienced coder.

I was trying to borrow code from the following page: https://level0gamedev.blogspot.com/2016/05/back-to-game-code.html

I'm also having a second issue of all 45 sprites being set to foo's sprite instead of 30 for foo and 15 for bar, but i'll have to tackle that later unless someone can weigh in on that as well.

Any help is greatly appreciated! Thank you :)

function _init()
test = 0

for i = 1, 30 do
	spawn_actor(foo)
end

for i = 1, 15 do
	spawn_actor(bar)
end	

function spawn_actor(name)
	local obj = {}

	obj.type = name
	obj.frame = nil
	obj.x = flr(rnd(right_border) + left_border)
	obj.y = flr(rnd(bottom_border - top_border) + top_border)
	obj.w = 8
	obj.h = 8
	obj.x2 = obj.x + obj.w * 8
	obj.y2 = obj.y + obj.h * 8

	if obj.name == foo then
		obj.frame = 16 + flr(rnd(3))
	elseif obj.name == bar then
		obj.frame = 32
	end

	overlapped = true
		while overlapped do
		overlapped = false
		foreach(actors, function(actors)
			if actors.x <= obj.x + obj.w * 8 + 1 and 
			actors.x + actors.w * 8 >= obj.x - 1 and 
			actors.y <= obj.y + obj.h * 8 + 1 and 
			actors.y + actors.h * 8 >= obj.y - 1 then
				test += 1
				overlapped = true
				obj.x = flr(rnd(right_border) + left_border)
				obj.y = flr(rnd(bottom_border - top_border) + top_border)
			end
		end)
	end
	add(actors, obj)
end

function _draw()
	cls()
	foreach (actors, draw_actor)
end

function draw_actor(obj)
	spr(obj.frame, obj.x, obj.y, 1, 1)
end


1.
obj.w = 8
obj.w * 8 <- 64 pixels!

2.
if you don't define 'foo' nor 'bar', all actors are named 'nil'


This is one of those cases where I took code from an existing game to try and work it in myself, which is why it was checking for such a large space (as I had mistaken size as being per pixel rather than per sprite), as well as things like "actors" being both the name of both the array and the foreach parameter.

That said, I changed the obj.w from 8 to 1 and it works now. Thank you for pointing this out to me.

I should also clarify that in the actual code, spawn_actor() does pass an actual name for the arguments, I simply changed them to foo and bar for this example.

Thanks again.



[Please log in to post a comment]