Hey there, i'm relatively new to pyGame and considering this is like my second attempt at doing it by myself after watching a few tutorials, i'd say im getting the hang of it.
However, as i was creating a game i realised i had no clue how to make the objects bounce off eachother and repel. Here is my code so far, i know it doesn't work and i know it seems quite stupid at the end, however i was just trying all sorts of things.
My way of interpreting this problem is that if there is an intersection that is equal on both shapes, It should repel, but as i've tried doing this i can only manage to get one intersection. I tried range function as you can see but that does not work, which i kinda knew wouldn't.
import pygame
import random
#Setting Basic Colors
black = (0,0,0)
white = (255,255,255)
#Intitalising PyGame
pygame.init()
#Setting Screen Settigns
size = [500,500]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("Bounce")
done = False
#Setting Initial Variables
clock=pygame.time.Clock()
rect_x = 50
rect_y = 50
change_x = 1
change_y = 1
circlex = random.randint(70,430)
circley = random.randint(70,430)
circchange_x = 0
circchange_y = 0
#----Main Game Loop----
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_x = 0
change_y = -2
if event.key == pygame.K_DOWN:
change_x = 0
change_y = 2
if event.key == pygame.K_LEFT:
change_x = -2
change_y = 0
if event.key == pygame.K_RIGHT:
change_x = 2
change_y = 0
screen.fill(black)
pygame.draw.rect(screen,white,[rect_x, rect_y,50,50])
#Rectangle stuff
rect_x += change_x
rect_y += change_y
if rect_x >= 450 or rect_x <= 0:
change_x = change_x*-1
if rect_y >= 450 or rect_y <= 0:
change_y = change_y*-1
pygame.draw.circle(screen,white,[circlex,circley],10,10)
circlex += circchange_x
circley += circchange_y
if circlex >= 490 or circlex <= 10:
circchange_x = circchange_x*-1
if circley >= 490 or circley <= 10:
circchange_y = circchange_y*-1
for i in range(rect_x+1,rect_x+51):
for j in range(circlex+1,circlex+11):
if i == j:
circchange_y = circchange_y*-1+1
circchange_x = circchange_x*-1+1
if i == j:
circchange_y = circchange_y*-1+1
circchange_x = circchange_x*-1+1
if i == j:
circchange_y = circchange_y*-1+1
circchange_x = circchange_x*-1+1
if i == j:
circchange_y = circchange_y*-1+1
circchange_x = circchange_x*-1+1
pygame.display.flip()
clock.tick(20)
pygame.quit()
Any help would be greatly apreciated :) Cheers