我写了一个由圆圈组成的代码。检查碰撞对墙壁的影响。但圆圈运动不正常。我使用rect的碰撞功能检查了碰撞。关于圆圈运动不正确的任何想法?有些圆圈正在移动,但当它们击中另一个圆圈时,它会粘在那个圆圈上并一起移动。 这是我的代码
import pygame,sys,math
from pygame.locals import *
import random
pygame.init()
screensize=(640,480)
screen=pygame.display.set_mode(screensize)
pygame.display.set_caption("swarm bots")
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
darkBlue = (0,0,128)
white = (255,255,255)
black = (0,0,0)
pink = (255,200,200)
colors = [red,green,blue,darkBlue,black,pink]
class robot():
def __init__(self,color,x,y,radius,speed,angle):
self.color=color
self.x=x
self.y=y
self.rect=pygame.Rect(self.x,self.y,40,40)
self.speed=speed
self.angle=angle
self.vx=0
self.vy=0
self.radius=radius
def update(self):
self.vx=self.speed*math.cos(self.angle)
self.vy=self.speed*math.sin(self.angle)
self.rect=self.rect.move(self.vx,self.vy)
self.hit_bounds = False
if (self.rect.centerx+self.radius >= screen.get_width()+ 40 or self.rect.centerx+self.radius <= 0):
self.hit_bounds = True
self.angle = random.randrange(0,360)
self.vx=0
self.vy=0
if (self.rect.centery+self.radius >= screen.get_height()+40 or self.rect.centery+self.radius <= 0):
self.hit_bounds =True
self.angle = random.randrange(0,360)
self.vx=0
self.vy=0
self.angle = self.angle % 360
for rob in robolist:
if not self.hit_bounds and not rob is self and self.rect.colliderect(rob.rect):
self.angle = random.randrange(0,360)
self.vx=0
self.vy=0
print("collide")
break
def draw(self):
pygame.draw.circle(screen,self.color,self.rect.center,int(self.radius),4)
#self.angle=self.angle-math.pi
#myrob=robot(green,100,100,25,5,random.randrange(0,360))
clock = pygame.time.Clock()
robolist=[]
pop=10
idindex=0
radiusUL = 20
radiusLL = 10
while (True):
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
pygame.quit(); sys.exit();
clock.tick(100)
# myrob.update()
while(len(robolist) < pop):
robolist.append(robot(colors[random.randrange(0,len(colors))],random.randrange(radiusUL+1,screensize[0]-radiusUL-1),random.randrange(radiusUL+1,screensize[1]-radiusUL-1),random.randrange(radiusLL,radiusUL),3,random.randrange(0,360)))
idindex+=1
screen.fill(white)
for i in robolist:
i.draw()
i.update()
#myrob.draw()
pygame.display.update()