Is There A Way To Get The Coordinates Of A Specific Object/click In Pygame?
Solution 1:
Add a list for the mouse positions:
points = []
Add the position to list when the mouse is clicked:
if e.type == MOUSEBUTTONDOWN:
if e.button == 1:
points.append(e.pos)
Draw the points in a loop:
for pos in points:
draw.circle(screen,GREEN, pos, 10)
If there are at least 2 points, then the lines between the points can be drawn by pygame.draw.lines()
:
iflen(points) > 1:
draw.lines(screen, GREEN, False, points)
Based on your previous question, I suggest the following:
from pygame import *
init()
size = width, height = 650, 650
screen = display.set_mode(size)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
running = True
myClock = time.Clock()
points = []
# Game Loopwhile running:
for e in event.get():
if e.type == QUIT:
running = Falseif e.type == MOUSEBUTTONDOWN:
if e.button == 1:
points.append(e.pos)
if e.button == 3:
points = []
screen.fill(BLACK)
iflen(points) > 1:
draw.lines(screen, GREEN, False, points)
for pos in points:
draw.circle(screen,GREEN, pos, 10)
display.flip()
myClock.tick(60)
quit()
Alternatively the clicked position can be stored (prev_pos
) and used the next time, when the mouse is clicked to draw a line.
I do not recommend this, because you'll lose the information about the clicked positions:
from pygame import *
init()
size = width, height = 650, 650
screen = display.set_mode(size)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
running = True
myClock = time.Clock()
prev_pos = None# Game Loopwhile running:
for e in event.get():
if e.type == QUIT:
running = Falseif e.type == MOUSEBUTTONDOWN:
if e.button == 1:
if prev_pos != None:
draw.line(screen, GREEN, prev_pos, e.pos)
prev_pos = e.pos
draw.circle(screen, GREEN, e.pos, 10)
if e.button == 3:
prev_pos = None
screen.fill(BLACK))
display.flip()
myClock.tick(60)
quit()
Solution 2:
I think that this will solve your problem: https://www.pygame.org/docs/ref/mouse.html
" pygame.mouse.get_pos() get the mouse cursor position get_pos() -> (x, y)
Returns the X and Y position of the mouse cursor. The position is relative to the top-left corner of the display. The cursorposition can be located outside of the display window, but is always constrained to the screen."
You can use pygame.draw.circle()
to draw a circle with a center at the point where the mouse is, and a polygon or lines if you'd like to connect them.
I hope this helps
Post a Comment for "Is There A Way To Get The Coordinates Of A Specific Object/click In Pygame?"