2016-03-18 132 views
0

我想在pygame中製作一種屏幕保護程序,泡泡在屏幕內彈跳,並且還彈跳對方。我怎樣才能做到這一點?下面是裏面的畫面彈跳部分:Pygame彈跳泡泡

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) 

回答

1

這可能工作:

  1. 檢查圓的中心之間的距離。 (如果它小於它們的半徑之和,則它會發生碰撞)要找到距離,請查找x或y像素距離。以像素爲單位的距離爲:

    sqrt((x_dist**2) + (y_dist**2)). 
    

http://i.stack.imgur.com/EFR8f.png

  • 如果它們被碰撞,啓動反彈。那麼,你需要物理學。請記住:力=質量(加速度),總能量=潛在能量+動能。儘管如此,我無法幫助你。只要改變x_dir和y_dir,取決於它們如何碰撞。實驗。

  • 隨時問我什麼! = D