Trying to add enemies to frog tutorial, struggling with behaviour (SOLVED)

Hi guys, first of all please forgive me, I’m a noob… I’m trying to get an enemy to fly down from the top right hand side of the screen, to the left, bounce off of the ground and fly back up off somewhere on the left side of the screen. I have tried many versions of the following conditional statement, but I can’t quite seem to get it right. Not sure if my rudimentary logic skills are faulty or if something else is going on:

-- A really long chunk of code
function update(self, dt)
	local p = go.get_position()	
        -- x stuff...
	if p.x < -500 then -- this is related to spawning this object from a factory
            msg.post("/level/controller#script", "delete_bugs", { id = go.get_id() })
        end
        p.x = p.x - speed * dt
        go.set_position(p)
    
    -- y stuff... 
        local down = true -- start by moving down
 	local top_limit = 700
	local bottom_limit = 100
 
	if down then
		p.y = p.y - speed * dt
		go.set_position(p)
		if p.y <= bottom_limit then
			down = false
			--print(p.y)
			--print(down)
		end
	end
	if not down then
		print("p.y before new velocity:", p.y)
		p.y = p.y + speed * dt
		go.set_position(p)
		print("p.y after new velocity:", p.y)
		if p.y >= top_limit then
			down = true
			print(down)
			print(p.y)
		end
	end
  end -- end of really long chunk of code

In this particular version, the enemy drops on an angle from the top right hand side of the screen, hits the ground and just stays at that level, floating across to the left hand side of the screen. The system seems to be reaching the “if not down” statement, at which point p.y = 99.999855041504 and then after the “p.y = p.y + speed * dt” line is executed p.y = 113.33319091797, but like I say it just stays there. I would expect that p.y would keep increasing until we hit the top_limit. Any input would be greatly appreciated. Thanks.

Because every time update() is called, the local down flag is always true. So when enemy reaches bottom_limit, it just down a little bit and up a little bit, until it is deleted by “delete_bugs” message.
You need change to the local down flag to go.property

3 Likes

Cheers Jarod! That seems obvious now that you pointed it out. I’m a little embarrassed but mostly very grateful. :+1: