i am trying to write a very basic program. there are 3 rectangles, when you clicked on one of them, it will be selected. but only one for each time. for instance, if one rectangle is selected and you clicked on another one or on blank area, it should return to unselected mode. my code is here, strangely only the blue box works right. where do i make the mistake?
Code: Select all
function love.load()
--defined colors
white={255,255,255,255}
red={255,0,0,255}
green={0,255,0,255}
blue={0,0,255,255}
activeRect=nil -->selected rectangle is kept here
--rectangles
rectA={
x=10,
y=10,
width=200,
height=50,
color=red,
tag="red rectangle",
active=false
}
rectB={
x=10,
y=70,
width=100,
height=50,
color=green,
tag="green rectangle",
active=false
}
rectC={
x=10,
y=130,
width=100,
height=50,
color=blue,
tag="blue rectangle",
active=false
}
end
function makeRect(rect) -->function that makes the rectangles
--some vars
local x,y,w,h,color,tag,r,g,b,a,active = rect.x,rect.y,rect.width,rect.height,rect.color,rect.tag,rect.color[1],rect.color[2],rect.color[3],rect.color[4],rect.active
--mouse click vars
local cursorX,cursorY,button=love.mouse.getX(),love.mouse.getY(),love.mouse.isDown("l")
--draws the rectangle and tags on them
love.graphics.setColor(r,g,b,a)
love.graphics.rectangle("fill",x,y,w,h)
love.graphics.setColor(white,255)
love.graphics.printf(tag,x,y,w,"center")
--PROBLEMATIC AREA STARTS
if active==false and cursorX>x and cursorX<x+w and cursorY>y and cursorY<y+h and button==true then
activeRect=rect
elseif (cursorX<x or cursorX>x+w or cursorY<y or cursorY>y+h) and button==true then
rect.active=false
activeRect=nil
end
if activeRect==rect then
love.graphics.setColor(white,255)
love.graphics.setLineWidth(2)
love.graphics.rectangle("line",x,y,w,h)
end
--PROBLEMATIC AREA ENDS
end
function love.draw()
--draws the rectangles
makeRect(rectA)
makeRect(rectB)
makeRect(rectC)
end