python - pygame中移动 Sprite 之间的碰撞

标签 python pygame sprite collision-detection

我有两个移动的 Sprite ,一个叫做墙,它只是上下移动;另一个叫做墙,它只是上下移动;另一个称为“玩家”,它会在屏幕上弹跳,并在遇到障碍物时改变方向。

我在一定程度上做到了这一点:玩家球确实会弹来弹去,但有时会出现一个错误,球似乎对运动感到困惑,并且在与墙壁碰撞时只是来回摆动。我将球员球的速度或墙的移动速度设置得越快,错误就会变得越频繁。

这是该项目的代码:

import pygame, sys

# The class that creates the player ball; it does not take user input but just bounces around
class Player(pygame.sprite.Sprite):
    def __init__(self, color, width, height,speed_x,speed_y):
        super().__init__()
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.speed_x = speed_x
        self.speed_y = speed_y

    def update(self,collision_group):
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        # code to get a bounce when the ball hits the edge of the screen
        if self.rect.right >= screen_width or self.rect.left <= 0:
            self.speed_x *= -1
        if self.rect.bottom >= screen_height or self.rect.top <= 0:
            self.speed_y *= -1

        # Code to get a bounce when the player collides with the wall
        collide_object = pygame.sprite.spritecollide(self,collision_group,False)
        if collide_object:
            if collide_object[0].rect.collidepoint(self.rect.midbottom) or collide_object[0].rect.collidepoint(self.rect.midtop):
                self.speed_y *= -1
        if collide_object[0].rect.collidepoint(self.rect.midright) or collide_object[0].rect.collidepoint(self.rect.midleft):
                self.speed_x *= -1          

# Code for the wall, it just moves up and down
class Wall(pygame.sprite.Sprite):
    def __init__(self,width,height,pos_x,pos_y,color):
        super().__init__()
        self.image = pygame.Surface([width,height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = pos_x
        self.rect.y = pos_y
        self.speed = 5

    def update(self):
        self.rect.y += self.speed

        if self.rect.bottom >= screen_height:
            self.speed *= -1 
        if self.rect.top <= 0:
            self.speed *= -1

# General setup
pygame.init()
clock = pygame.time.Clock()

# Game Screen
screen_width = 800
screen_height = 800
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Side by side collision")

# Creating the sprites and groups
moving_sprites = pygame.sprite.Group()
player = Player((255,0,0),20,20,8,8)
moving_sprites.add(player)

wall_sprites = pygame.sprite.Group()
center_wall = Wall(500,200,300,300,(255,255,0))
wall_sprites.add(center_wall)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Drawing
    screen.fill((0,0,0))
    wall_sprites.draw(screen)
    wall_sprites.update()
    moving_sprites.draw(screen)
    moving_sprites.update(wall_sprites)

    pygame.display.flip()
    clock.tick(60)

提前非常感谢:)

最佳答案

您会发现,如果墙壁在碰撞时远离玩家,您的代码就能完美运行。当他们相互靠近时就会出现问题。这是因为你的玩家实际上进入了墙内,你检测到碰撞,反转玩家的速度,并且在下一次迭代时你的玩家仍然在墙内(因为墙正在向你的玩家移动,玩家无法找到有足够的时间逃脱它)并且您再次检测到碰撞,反转玩家的速度...

您可以这样修改代码来解决问题:

if collide_object:
    rect = collide_object[0].rect
    if rect.collidepoint(self.rect.midbottom): # if we hit from bottom
        if self.speed_y > 0: # and the player was moving down
            self.speed_y *= -1 # go up
    elif rect.collidepoint(self.rect.midtop): # if we hit from top
        if self.speed_y < 0: # and the player was moving up
            self.speed_y *= -1 # go down

关于python - pygame中移动 Sprite 之间的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61699253/

相关文章:

ios - 以圆形图案拍摄物体 SpriteKit

python - 在pygame应用程序中显示文本文件中的单词

sdl - 如何在 Raspberry Pi 上使用 dispmanx 创建透明窗口?

python - (Python) 检查数独中的 3x3,有更好的方法吗?

python - PyQt5 - 组合框中有条件的颜色字段 - qsqltablemodel

python - 蛇的问题 - 运动

python - 如何使表面(次表面)围绕矩形居中? (缩放 Sprite 碰撞箱/碰撞矩形)

graphics - 在 Monogame 中从 PNG 加载纹理的透明度问题

python - 自定义Python切片,请指教

python - 为什么在 IF 条件后出现 'Invalid syntax' 错误?