I’m trying to implement drawing boxes in a program, like when you hold a mouse button and there is a rectangle when you move the mouse around. Trying to do it with a pygame rect object and this is what I’ve come up with so far:
def mouseDown(self, button, pos):
if button == 1:
self.pressing = True
self.start = pos
def mouseUp(self, button, pos):
if button == 1:
self.pressing = False
def mouseMotion(self, buttons, pos):
if self.pressing == True:
width = abs(self.start[0] - pos[0])
height = abs(self.start[1] - pos[1])
self.box = pygame.Rect(self.start, width, height)
pygame.draw.rect(self.screen, (0,0,0), self.box, 1)
So pos is the coordinates of the click, with (0,0) being top left corner. I tried to use abs to get the size by comparing how far the mouse has moved, but abs only returns positive values, and therefor it doesn’t work.
How can we change this to make box selection possible?
Using Calums very helpful answer as a stepping stone, I came up with this solution: