Location of the objects that are moving - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Game Development (https://python-forum.io/forum-11.html) +--- Thread: Location of the objects that are moving (/thread-32277.html) |
Location of the objects that are moving - rturus - Feb-01-2021 I have the following code. I would like to add scoring point whenever two rectangles collided with each other. I am finding difficult to get the location of the rectangles while they are moving. Any idea how I can do that? Thanks, Ronnie import pygame import sys from pygame.locals import* pygame.init() screen=pygame.display.set_mode((600,500)) pygame.display.set_caption("Drawing Rectangle") pos_x=300 pos_y=250 pos_z=100 pos_w=50 vel_x=2 vel_y=1 vel_m=2 vel_n=1 while True: for event in pygame.event.get(): if event.type in (QUIT,KEYDOWN): pygame.quit() sys.exit() screen.fill((0,0,200)) pos_x+=vel_x pos_y+=vel_y pos_z+=vel_m pos_w+=vel_n if pos_x>500 or pos_x<0: vel_x=-vel_x if pos_z>500 or pos_z<0: vel_m=-vel_m if pos_y>400 or pos_y<0: vel_y=-vel_y if pos_w>400 or pos_w<0: vel_n=-vel_n color=255,255,0 col=150,100,150 width=0 pos=pos_x,pos_y,50,50 po=pos_z,pos_w,30,30 pygame.draw.rect(screen,color, pos,width) pygame.draw.rect(screen,col, po,width) pygame.display.update() RE: Location of the objects that are moving - nilamo - Feb-01-2021 If you use a Rect instead of just drawing a rect each frame, you can use Rect.colliderect() to handle collision detection for you (I added a clock, to make testing easier): import pygame import sys pygame.init() screen = pygame.display.set_mode((600, 500)) pygame.display.set_caption("Drawing Rectangle") pos_x = 300 pos_y = 250 pos_z = 100 pos_w = 50 vel_x = 2 vel_y = 1 vel_m = 2 vel_n = 1 big_rect = pygame.Rect(pos_x, pos_y, 50, 50) small_rect = pygame.Rect(pos_z, pos_w, 30, 30) clock = pygame.time.Clock() collided_last_frame = False while True: for event in pygame.event.get(): if event.type in (pygame.QUIT, pygame.KEYDOWN): pygame.quit() sys.exit() screen.fill((0, 0, 200)) pos_x += vel_x pos_y += vel_y pos_z += vel_m pos_w += vel_n if pos_x > 500 or pos_x < 0: vel_x = -vel_x if pos_z > 500 or pos_z < 0: vel_m = -vel_m if pos_y > 400 or pos_y < 0: vel_y = -vel_y if pos_w > 400 or pos_w < 0: vel_n = -vel_n color = 255, 255, 0 col = 150, 100, 150 big_rect.left = pos_x big_rect.top = pos_y small_rect.left = pos_z small_rect.top = pos_w collision = big_rect.colliderect(small_rect) if collision and not collided_last_frame: print("rects collided!") collided_last_frame = collision pygame.draw.rect(screen, color, big_rect) pygame.draw.rect(screen, col, small_rect) pygame.display.update() clock.tick(120) |