Can't detect when mouse hovers over an object?
Posted: Tue Jul 06, 2021 8:52 pm
Beginner question alert.
I can't seem to detect when the mouse hovers over a pawn.
I have a similar class called button that works the same way, and functions just fine.
The problematic code:
The working code:
I can't seem to detect when the mouse hovers over a pawn.
I have a similar class called button that works the same way, and functions just fine.
The problematic code:
Code: Select all
Pawn = Class{}
pawns = {}
function pawns:init(x1, y1, x2, y2, x3, y3, type, controller, name, inplay)
local newPawn = {
x1 = x1,
y1 = y1,
x2 = x2,
y2 = y2,
x3 = x3,
y3 = y3,
controller = controller,
type = type,
inplay = inplay,
place = "none",
hot = false
}
table.insert(pawns, newPawn)
end
function pawns:update(dt)
local mx, my = love.mouse.getPosition()
for i,v in ipairs(pawns) do
if mx > pawns[i].x1 and mx < pawns[i].x2 then
if my > pawns[i].y1 and my < pawns[i].y3 then
pawns[i].hot = true
currentlyFocused = self
print("a pawn is hot")
else
pawns[i].hot = false
end
else
pawns[i].hot = false
end
end
end
function pawns:render()
pawns:flash()
for i,v in ipairs(pawns) do
-- defining a table with the coordinates
local vertices = {pawns[i].x1, pawns[i].y1,
pawns[i].x2, pawns[i].y2, pawns[i].x3, pawns[i].y3}
if pawns[i].inplay == true then
-- passing the table to the function as a second argument
love.graphics.polygon('fill', vertices)
end
end
end
-- flash if hot function
function pawns:flash()
for i,v in ipairs(pawns) do
if pawns[i].hot == true then
love.graphics.setColor(0.5, 1, 0.5, 1)
else
love.graphics.setColor(0, 0, 0, 1)
end
end
end
Code: Select all
Button = Class{}
function Button:init(x, y, width, height, name, red, green, blue, action)
self.x = x
self.y = y
self.width = width
self.height = height
self.name = name
self.red = red
self.green = green
self.blue = blue
self.action = action
self.hot = false
end
function Button:update(dt)
local mx, my = love.mouse.getPosition()
if mx > self.x and mx < self.x + self.width then
if my > self.y and my < self.y + self.height then
self.hot = true
currentlyFocused = self
print("a ui button is hot")
else
self.hot = false
end
else
self.hot = false
end
end
function Button:click()
if self.hot == true then
self.action()
end
end
function Button:render()
-- set rect color and print
-- if hot then flash
self:flash()
love.graphics.rectangle("fill", self.x, self.y, self.width, self.height)
-- set text color and print
love.graphics.setColor(1, 1, 1, 1)
love.graphics.setFont(mainFont)
love.graphics.printf(tostring(self.name), self.x, self.y, self.width, "center")
end
-- next turn function
function nextTurn()
if pTurn == playerNum then
pTurn = 1
else
pTurn = pTurn + 1
end
end
-- flash if hot function
function Button:flash()
if self.hot == true then
love.graphics.setColor(self.red, 1, self.blue, 1)
else
love.graphics.setColor(self.red, self.green, self.blue, 1)
end
end