This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
H4X0RZ's profile picture

Checking If A Point On An Image Is Clicked

Started by H4X0RZ, 20 September 2013 - 09:44 AM
H4X0RZ #1
Posted 20 September 2013 - 11:44 AM
Hello com,
I'm working on a game and I want to check if the user has clicked a specific position on the screen. The position(s) is/are an image drawn with the paint program.
I want to check if the click was on the image.

I'm doing something like this but it don't works:

local img = paintutils.loadImage("someImage")
local clickCount = 1
local function draw()
while true do
  paintutils.drawImage(img)
  sleep(0.1)
end
end
local function click()
while true do
  local _,btn,x,y = os.pullEvent()
  if _ == "mouse_click" then
   if img[y][x] == colors.brown then
    clickCount = clickCount + 1
   end
  end
  sleep(0)
end
end
Does anybody know what I'm doing wrong?
BigTwisty #2
Posted 20 September 2013 - 02:29 PM
The problem is with this line:

local function click()

This sets up the rest of the code as a function which is then never called by your program. Easiest solution is to just add "click()" to the bottom of the code. Better would be to remove "local function click()" and the last "end".

Edit: Better use of indentation might help you a lot. For example:

local img = paintutils.loadImage("someImage")
local clickCount = 1
local function draw()
  while true do
    paintutils.drawImage(img)
    sleep(0.1)
  end
end
while true do
  local id,btn,x,y = os.pullEvent()
  if id == "mouse_click" then
    if img[y][x] == colors.brown then
      clickCount = clickCount + 1
    end
  end
  sleep(0)
end

Do you see how the extra tabbing helps you to see where the functions start and end?
MKlegoman357 #3
Posted 20 September 2013 - 03:03 PM
I think, you are missing parallel API usage in your program:

parallel.waitForAll(draw, click)

EDIT:
First goes y, then x coordinates.

Next, I think that this:

if img[y][x] == colors.brown then

should be that:

if img[x][y] == colors.brown then

--//First y then x.
Edited on 20 September 2013 - 01:09 PM
H4X0RZ #4
Posted 20 September 2013 - 04:46 PM
I think, you are missing parallel API usage in your program:

parallel.waitForAll(draw, click)
-snip-
Yep, I forgot the parallel call in my code above :D/>
BigTwisty #5
Posted 21 September 2013 - 12:58 AM
Why draw the image over and over again?
H4X0RZ #6
Posted 21 September 2013 - 03:10 AM
Why draw the image over and over again?
Because I want to add a menu and then it has to be redrawn every time :D/>
Lyqyd #7
Posted 21 September 2013 - 03:29 AM
Why not draw the image in your event loop, just before pulling an event? And remove the sleep(0) from your event handling loop.