For loop inside love.update is not working as i think
Posted: Fri Sep 11, 2015 6:06 am
Hi, I've never made a forum post so if I do/say something that I'm not supposed to or if I'm not clear enough, please forgive me.
What I'm trying to do is to place "wires" in the map (which is a grid of 16x16px). I tried to make it impossible to place a wire above another wire, but my code is not working as I expect. I made a for loop to check for all instances positions and compare them to the cursor position (Not the mouse position), but it only runs once and stays in the last placed instance.
This is my code:
I uploaded the love file.
Thanks.
What I'm trying to do is to place "wires" in the map (which is a grid of 16x16px). I tried to make it impossible to place a wire above another wire, but my code is not working as I expect. I made a for loop to check for all instances positions and compare them to the cursor position (Not the mouse position), but it only runs once and stays in the last placed instance.
This is my code:
Code: Select all
function love.load()
-- Require modules
require("wire")
-- Load the sprites for the components
wire_sprite = {}
for i=0,10 do
wire_sprite[i] = love.graphics.newImage("images/wire_" .. i .. ".png")
end
-- Some useful vars
screenWidth, screenHeight = love.window.getDimensions()
mouse_x = love.mouse.getX()
mouse_y = love.mouse.getY()
cursor_x, cursor_y = 2,2
fps = love.timer.getFPS()
can_click = true
-- Object update list
instanceList = {}
-- Draw the background and shit
love.graphics.setBackgroundColor(255,255,255,255)
love.window.setMode(800, 600, {resizable=true, vsync=true, minwidth=800, minheight=600})
end
function instance_get()
for i = 1,#instanceList do
return instanceList[i]
end
end
function love.update(dt)
-- Update the mouse, cursor, and fps positions
screenWidth, screenHeight = love.window.getDimensions()
fps = love.timer.getFPS()
mouse_x = love.mouse.getX()
mouse_y = love.mouse.getY()
cursor_x = math.floor(mouse_x / 16)
cursor_y = math.floor(mouse_y / 16)
-- Update the instances
for i = 1,#instanceList do
instanceList[i]:update()
end
for i = 1,#instanceList do
if instanceList[i].x == cursor_x and instanceList[i].y == cursor_y then
can_click = false
else can_click = true
end
end
if love.mouse.isDown("l") and can_click then
instanceList[#instanceList+1] = Wire:new(cursor_x,cursor_y)
end
end
function love.draw()
-- Debug
love.graphics.print("Instances: " .. #instanceList, 4, 4)
love.graphics.print("Cursor: " .. "(" .. cursor_x .. "," .. cursor_y .. ")", 4, 16)
love.graphics.print("FPS: " .. fps, 4, 16+12)
if #instanceList > 1 then
love.graphics.print("Can Click: " .. tostring(can_click), 4, 16+24)
end
-- Draw the instances
for i = 1,#instanceList do
instanceList[i]:draw()
end
love.graphics.setColor(0,0,100,70)
for x=1,screenWidth/16 do
love.graphics.line(x*16, 1, x*16, screenHeight)
end
for y=1,screenHeight/16 do
love.graphics.line(1, y*16, screenWidth, y*16)
end
love.graphics.setColor(70,70,70,255)
end
Thanks.