[英]Can't seem to discover how to add collisions to Pygame
我能找到的所有教程都不适用于我。 如果有人可以提供帮助,那就太好了。 我的主要目标是制作一款有点像吃豆人的游戏,但我无法解决碰撞问题。 我对 pygame 和 python 有点陌生。 目前我只希望黄色圆圈不是 go 通过蓝色矩形。 如果您知道如何执行此操作,请再次告诉我。 我有点菜鸟,我找不到任何有效的例子。 提前致谢!
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Pyman by Jonathan Curtis")
x = 50
y = 50
radius = 10
speed = 5
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
def mazeWall(startx, starty, endx, endy):
pygame.draw.line(win, BLUE, (startx, starty), (endx, endy), 10)
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_x]:
print(x)
if keys[pygame.K_y]:
print(y)
if keys[pygame.K_LEFT] or keys[pygame.K_a]:
x -= speed
if keys[pygame.K_RIGHT] or keys[pygame.K_d] and not rightCollide:
x += speed
if keys[pygame.K_UP] or keys[pygame.K_w]:
y -= speed
if keys[pygame.K_DOWN] or keys[pygame.K_s]:
y += speed
#Makes it impossible to go off the screen.
if x > 480:
x = 480
if x < 20:
x = 20
if y > 480:
y = 480
if y < 20:
y = 20
#Draws character
win.fill((0, 0, 0))
pygame.draw.circle(win, YELLOW, (x, y), radius)
#Draws the maze border
mazeWall(0, 1, 500, 1)
mazeWall(0, 1, 0, 500)
mazeWall(0, 499, 500, 499)
mazeWall(500, 0, 500, 500)
#Draws the rectangle
mazeWall(100, 50, 200, 50)
pygame.display.update()
pygame.quit()
将您的迷宫墙转换为数据结构 / class。 或者甚至只是将它们保留为pygame.Rect的列表。 还要在您的播放器对象周围维护一个 Rect 。
例如:
maze_walls = [ pygame.Rect(0, 1, 500, 1),
pygame.Rect(0, 1, 0, 500),
pygame.Rect(0, 499, 500, 499),
pygame.Rect(500, 0, 500, 500),
pygame.Rect(100, 50, 200, 50) ]
# this needs to have it's position updated when x & y change.
player_rect = pygame.Rect( x-radius, y-radius, 2*radius, 2*radius )
这将允许代码使用内置的 function pygame.Rect.colliderect()和/或pygame.rect.collidelist()来检查碰撞。
因此,这为以下墙壁提供了一个绘图循环:
#Draws character
win.fill((0, 0, 0))
pygame.draw.circle(win, YELLOW, (x, y), radius)
#Draws walls
for wall in maze_walls:
pygame.draw.rect( win, BLUE, wall )
pygame.display.update()
所以要检查你的播放器和墙壁之间的碰撞,遍历墙壁检查每一个是相当简单的:
# Did the player hit a wall
player_rect.center = (x, y)
for wall in maze_walls:
if ( player_rect.colliderect( wall ) ):
print( "Player hits wall: "+str( wall ) )
# TODO: stop movement, whatever
当然,使用PyGame Sprites有更好的方法来做到这一点,但我试图让答案与您的代码现在所做的最接近,同时尽可能保持简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.