我只是想知道碰撞在游戏中是如何工作的。我是python的新手,在碰撞检测和矩形分辨率方面遇到了一些麻烦。我正在尝试使矩形不重叠。我不希望它们出现反弹的效果。我不想使用pygame的任何内置功能来解决冲突或任何游戏引擎。您能帮我使我的代码更有效吗?
这里是代码:
import pygame
pygame.init()
screen_height = 500
screen_width = 500
window = pygame.display.set_mode((screen_width, screen_height))
class Player():
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.velocity = 5
self.collision = False
self.tempX = self.x
self.tempY = self.y
self.dirX = 0
self.dirY = self.y
player = Player(20, 20 ,50, 50)
collider = Player(90, 90, 50, 50)
velocity = 5
def movement():
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.y -= player.velocity
elif keys[pygame.K_DOWN]:
player.y += player.velocity
if keys[pygame.K_RIGHT]:
player.x += player.velocity
elif keys[pygame.K_LEFT]:
player.x -= player.velocity
def draw():
window.fill((0, 0, 0))
pygame.draw.rect(window, (0, 0, 255), (player.x, player.y, player.width, player.height))
pygame.draw.rect(window, (0, 255, 0), (collider.x, collider.y , player.width, player.height))
pygame.display.update()
def collisionDetection():
if player.y >= collider.y - player.height and player.y < collider.y:
if player.x + player.width > collider.x and player.x < collider.x + collider.width:
player.y = collider.y - player.height
elif player.y <= collider.y + collider.height and player.y > collider.y:
if player.x + player.width > collider.x and player.x < collider.x + collider.width:
player.y = collider.y + collider.height
if player.x + player.width >= collider.x and player.x < collider.x:
if player.y > collider.y - player.height and player.y < collider.y + collider.height:
player.x = collider.x - player.width
elif player.x <= collider.x + collider.width and player.x > collider.x:
if player.y + player.height > collider.y and player.y < collider.y + collider.height:
player.x = collider.x + collider.width
def temporary():
player.tempX = player.x
player.tempY = player.y
mainloop = True
while mainloop:
pygame.time.delay(5)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
if player.collision == False:
movement()
draw()
collisionDetection()
temporary()
内置函数通常比您自己的要好,因为它们已经过优化。我建议为您的播放器使用pygame.Rect
类。这不仅可以简化对player.x的调用,还可以使用Rect.colliderect()
(如the docs中所述)
如果任一矩形的任何部分重叠,则返回true(顶部+底部或左侧+右侧)。
因此,您可以使用以下代码代替collisionDetection
函数:
rect1.colliderect(rect2)
如果文档离线,则可以使用Google cache version.