Reputation:
I want to make a kind of screen-saver in pygame, where bubbles bounce inside the screen, and also bounce against each other. How can i do this? Below is the part for bouncing inside the screen:
import pygame
from pygame.locals import *
WIDTH=1
TV_SIZE=(800,900)
pygame.init()
CLOCK=pygame.time.Clock()
TV=pygame.display.set_mode(TV_SIZE)
class Ball(object):
def __init__(self,pos_x,x_dir,pos_y,y_dir,color,radius):
self.pos_x=pos_x
self.x_dir=x_dir
self.pos_y=pos_y
self.y_dir=y_dir
self.color=color
self.radius=radius
def move(self):
if self.pos_x>=TV_SIZE[0]-self.radius or self.pos_x<=self.radius:
self.x_dir=-self.x_dir
self.pos_x+=self.x_dir
if self.pos_y>=TV_SIZE[1]-self.radius or self.pos_y<=self.radius:
self.y_dir=-self.y_dir
self.pos_y+=self.y_dir
else:
self.pos_x+=self.x_dir
self.pos_y+=self.y_dir
pygame.draw.circle(TV,self.color,(self.pos_x,self.pos_y),self.radius,WIDTH)
pygame.display.flip()
ball_1=Ball(100,5,100,5,(100,100,100),50)
ball_2=Ball(31,8,31,8,(200,200,100),30)
while True:
for e in pygame.event.get():
if e.type==QUIT:
pygame.quit()
ball_1.move()
ball_2.move()
TV.fill((0,0,0))
CLOCK.tick(30)
Upvotes: 0
Views: 582
Reputation: 122
This could work:
Check if the distance between the circle's centers. (If it is less than the sum of their radiuses, it is colliding) To find distances, find x or y pixel distances. The distance in pixels is:
sqrt((x_dist**2) + (y_dist**2)).
https://i.sstatic.net/EFR8f.png
If they are colliding, start the bounce. Then, you need physics. Remember: force = mass(acceleration), Total Energy = Potential Energy + Kinetic Energy. I can't really help you there, though. Just change x_dir and y_dir depending on how they collide. Experiment.
Feel free to ask me anything! =D
Upvotes: 1