Aug-13-2021, 09:22 AM
I would like to make the moveable rectangle r0 snap to the other rectangle corners when I move it near them with the mouse.
That is, if say any corner of my rectangle r0 gets near a corner of r1, then set the position of r0 to that corner.
I can't see how to achieve this.
Maybe create a bigger, unseen version of r0 and if it collides with a corner of r1, set that point as r0.x, r0.y ???
That is, if say any corner of my rectangle r0 gets near a corner of r1, then set the position of r0 to that corner.
I can't see how to achieve this.
Maybe create a bigger, unseen version of r0 and if it collides with a corner of r1, set that point as r0.x, r0.y ???
import pygame
from pygame.locals import *
from pygame.rect import *
def rectMM3():
pygame.init()
width = 600
height = 600
SIZE = (500, 200)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
GRAY = (150, 150, 150)
WHITE = (255, 255, 255)
# set the font
font = pygame.font.Font(None, 24)
screen = pygame.display.set_mode((width, height))
pts = ('topleft', 'topright', 'bottomleft', 'bottomright')
def draw_text(text, pos):
img = font.render(text, True, BLACK)
screen.blit(img, pos)
running = True
r0 = Rect(50, 60, 200, 80)
print(f'x={r0.x}, y={r0.y}, w={r0.w}, h={r0.h}')
r1 = Rect(100, 20, 100, 140)
print(f'x={r1.x}, y={r1.y}, w={r1.w}, h={r1.h}')
#r3 = Rect(40, 500, 220, 100)
moving = False
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == MOUSEBUTTONDOWN:
if r0.collidepoint(event.pos):
moving = True
elif event.type == MOUSEBUTTONUP:
moving = False
elif event.type == MOUSEMOTION and moving:
r0.move_ip(event.rel)
screen.fill(GRAY)
pygame.draw.rect(screen, RED, r0)
pygame.draw.rect(screen, CYAN, r1)
if moving:
pygame.draw.rect(screen, BLUE, r0, 4)
pygame.draw.rect(screen, GREEN, r0, 4)
pygame.draw.rect(screen, GREEN, r1, 4)
for pt in pts:
pos1 = eval('r0.' + pt)
pos2 = eval('r1.' + pt)
draw_text(pt, pos1)
draw_text(pt, pos2)
# number at the end is the radius
pygame.draw.circle(screen, RED, pos1, 3)
pygame.draw.circle(screen, CYAN, pos2, 4)
pygame.display.flip()
pygame.quit()
