我一直在从事一个简单的Pygame项目,该项目涉及在开放区域模拟运动传感器灯,并创建了多个送货乘客、吸烟者和平民的实例.当用户在一定距离内时,地面上的灯就会亮起来.我面临的问题是,当对象与驱动程序发生碰撞时,CollizeRect根本不会触发(使用打印语句进行测试).理想情况下,除了司机和吸烟者之外,所有的平民都应该相互碰撞和反思.

下面是我的虚拟样机的录音:

Display setup and distance function

screen = width,height = 800,600
fps = 60 
cellsize = 50 
padding = 40 # create identations from the window 
rows = cols = (width - 50) // cellsize 
print(rows, cols) 

def euclid_dist(mX, mY, x, y): # distance to grid 
        dist = math.sqrt((mX - x)**2 + (mY - y)**2)

        if dist <= 80: 
            return True
        else: 
            return False 

Instantiation of objects

class Cell_1: # sample of user object 
    def __init__(self):
        self.x = random.randrange(20, width-20) #x position
        self.y = random.randrange(20, height-20) #y position
        self.x_speed = 2
        self.y_speed = 2 

        self.image = char # pre-loaded img 
        self.image = pygame.transform.scale(self.image, (cellsize, cellsize+20))
        self.rect = pygame.Surface.get_rect(self.image, center= (self.x, self.y))

    def wander(self):
        self.x += self.x_speed 
        self.y += self.y_speed

        if self.x <= 30 or self.x >= width - 30:
            self.x_speed *= -1 

        elif self.y <= 30 or self.y >= height - 30:
            self.y_speed *= -1

    def draw(self): 
        surface.blit(self.image, (self.x, self.y))

class Cell_2: 
    def __init__(self):
        self.x = random.randrange(20, width-20) #x position
        self.y = random.randrange(20, height-20) #y position
        self.x_speed = 2
        self.y_speed = 2 

        self.image = char # pre-loaded img 
        self.image = pygame.transform.scale(self.image, (cellsize, cellsize+20))
        self.rect = pygame.Surface.get_rect(self.image, center= (self.x, self.y))

    def wander(self):
        self.x += self.x_speed 
        self.y += self.y_speed

        if self.x <= 30 or self.x >= width - 30:
            self.x_speed *= -1 

        elif self.y <= 30 or self.y >= height - 30:
            self.y_speed *= -1

    def draw(self): 
        surface.blit(self.image, (self.x, self.y))


class Driver: 
    # make driving linear 
    def __init__(self):
        self.x = random.randrange(20, width-20) #x position
        self.y = height - 20 #bottom of screen 
        self.y_speed = 12
        self.x_speed = 12

        self.image = char3
        self.image = pygame.transform.scale(self.image, (cellsize+20, cellsize+20))
        self.rect = pygame.Surface.get_rect(self.image, center = (self.x, self.y))

    def wander(self):
        if self.y <= 20: # height 
            self.y = height 
            self.x = random.randrange(20, width-20)

        else: 
            self.y -= self.y_speed

    def draw(self): 
        surface.blit(self.image, (self.x, self.y))

rects = [] 
cells_1 = []
for i in range(2): 
    cell = Cell_1()
    cells_1.append(cell)
    rects.append(cell) # for collision detection 

cells_2 = []
for i in range(2): 
    cell = Cell_2()
    cells_2.append(cell)
    rects.append(cell)

driver = Driver()

Running the game

while running:
    warm_col = (255, random.randint(0, 255), 0)
    surface.fill(black)

    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            # upon closing the window with mouse 
            running = False 

    driver.wander()
    driver.draw() 
        
    for npc in cells_1: 
        npc.wander()
        npc.draw()

    for npc in cells_2: 
        npc.wander()
        npc.draw()

    for rectangle in rects:
        if (rectangle.rect.colliderect(driver.rect)): 
            rectangle.x_speed *= -1 
            rectangle.y_speed *= -1 
        
    (mX, mY) = pygame.mouse.get_pos()
    char1 = pygame.transform.scale(char1, (cellsize-10, cellsize+20)) 
    surface.blit(char1, (mX, mY))

    for row in range(rows): 
        for col in range(cols): 
            for i in rects: 
                    x = col * cellsize + padding
                    y = row * cellsize + padding 
                    within_dist = euclid_dist(mX, mY, x, y)
                    npc_within = euclid_dist(i.x, i.y, x, y) 

                    if within_dist == True or npc_within == True:
                        pygame.draw.circle(surface, warm_col, (x,y), 3) 


for row in range(rows): 
        for col in range(cols): 
            for i in cells_1: 
                    x = col * cellsize + padding
                    y = row * cellsize + padding 
                    within_dist = euclid_dist(mX, mY, x, y)
                    npc_within = euclid_dist(i.x, i.y, x, y) 

                    if within_dist == True or npc_within == True:
                        pygame.draw.circle(surface, warm_col, (x,y), 3) 

    for row in range(rows): 
        for col in range(cols): 
            for i in cells_2: 
                    x = col * cellsize + padding
                    y = row * cellsize + padding 
                    within_dist = euclid_dist(mX, mY, x, y)
                    npc_within = euclid_dist(i.x, i.y, x, y) 

                    if within_dist == True or npc_within == True:
                        pygame.draw.circle(surface, warm_col, (x,y), 3) 

    for row in range(rows): 
        for col in range(cols):  
                    x = col * cellsize + padding
                    y = row * cellsize + padding 
                    within_dist = euclid_dist(mX, mY, x, y)
                    npc_within = euclid_dist(driver.x, driver.y, x, y) 

                    if within_dist == True or npc_within == True:
                        pygame.draw.circle(surface, warm_col, (x,y), 3)   

              

    pygame.display.update() 
    pygame.time.Clock().tick(fps) 
    pygame.mouse.set_visible(False) 

pygame.quit()

我try 过欧几里德距离,但它只适用于显示器的边缘(gif)

请问有没有更有效的方法?我想用精灵而不是blit,但不确定会不会有什么不同.另外,我是Pygame的新手,所以任何帮助或建议都将不胜感激!

推荐答案

在碰撞测试之前,必须更新矩形的位置:

driver.rect.x = round(self.y)
driver.rect.y = round(self.y)
for rectangle in rects:
    rectangle.rect.x = round(rectangle.x)
    rectangle.rect.y = round(rectangle.y)
    if rectangle.rect.colliderect(driver.rect): 
        rectangle.x_speed *= -1 
        rectangle.y_speed *= -1 

Python相关问答推荐

判断两极中N(N 2)列水平是否相等

Python:MultiIndex Dataframe到类似json的字典列表

仅对matplotlib的条标签中的一个条标签应用不同的格式

根据在同一数据框中的查找向数据框添加值

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

运行Python脚本时,用作命令行参数的SON文本

2D空间中的反旋算法

如何在虚拟Python环境中运行Python程序?

Telethon加入私有频道

Pandas:将多级列名改为一级

在ubuntu上安装dlib时出错

如何在Python中找到线性依赖mod 2

未知依赖项pin—1阻止conda安装""

从嵌套的yaml创建一个嵌套字符串,后面跟着点

如何在BeautifulSoup/CSS Select 器中处理regex?

在Admin中显示从ManyToMany通过模型的筛选结果

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

关于两个表达式的区别

pandas:在操作pandora之后将pandora列转换为int

如何求相邻对序列中元素 Select 的最小代价