我正在尝试使用 pymunk 和 pygame 编写程序。该程序(截至目前)只是一辆有一些障碍物的汽车。我正在尝试使用 pymunk 检查汽车和任何障碍物是否发生碰撞,如果发生碰撞,我将调用其他一些函数。我遇到的问题是汽车和/或障碍物似乎没有被添加到空间中。
这是我目前正在运行的代码,我为草率道歉。
谢谢
编辑:我的目标是使用 pymunk 来检测障碍物和汽车之间的碰撞,以返回类似“游戏结束”的东西。问题是我不知道障碍物和/或汽车是否被添加到 pymunk 空间。
import pygame as pg
import pymunk
import random
import numpy as np
pg.init()
display_width = 1500
display_height = 1000
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 100)
gameDisplay = pg.display.set_mode((display_width, display_height))
clock = pg.time.Clock()
carImg = pg.image.load('photoshop_car.jpg')
carImg.set_colorkey(black)
rectangles = []
space = pymunk.Space()
def draw_car(x, y):
pg.draw.circle(gameDisplay, blue, (x, y), 25)
def forward_movement_x(theta_degrees, movement_speed, currentx):
theta_radians = theta_degrees * (np.pi / 180)
delta_x = movement_speed * np.sin(theta_radians)
return delta_x
def forward_movement_y(theta_degrees, movement_speed, currenty):
theta_radians = theta_degrees * (np.pi / 180)
delta_y = movement_speed * np.cos(theta_radians)
return delta_y
def draw_obs(num_obs):
for i in range(num_obs):
obstaclex = random.randrange(0, display_width)
obstacley = random.randrange(0, display_height)
obstacle_width = random.randrange(50, 75)
obstacle_height = random.randrange(50, 75)
rectangles.append((obstaclex, obstacley, obstacle_width, obstacle_height))
return rectangles
def obs_to_space(space):
for i in rectangles:
body = pymunk.Body(body_type = pymunk.Body.STATIC)
obstacle_in_space = pymunk.Poly.create_box(body, size = (i[0], i[1]))
body.position = (i[0], display_height - i[1])
space.add(obstacle_in_space)
def car_to_space(x, y):
mass = 10
radius = 25
moment = pymunk.moment_for_circle(mass, 0, radius)
body = pymunk.Body(mass, moment)
body.position = (x, y)
shape = pymunk.Circle(body, radius)
space.add(body, shape)
def coll_begin(arbiter, space, data):
print("begin")
return True
def coll_pre(arbiter, space, data):
print("pre")
return True
def coll_post(arbiter, space, data):
print("pre")
def coll_separate(arbiter, space, data):
print("pre")
def game_loop():
gameExit = False
draw_obs(5)
x = (display_width * .5)
y = (display_height * .5)
car_rotation = 0
rotate_speed = 0
car_speed = 10
car_direction = True
obs_to_space(space)
while not gameExit:
gameDisplay.fill(pg.Color("black"))
for i in range(len(rectangles)):
pg.draw.rect(gameDisplay, red, rectangles[i])
for event in pg.event.get():
if event.type == pg.QUIT:
gameExit = True
if event.type == pg.KEYDOWN:
if event.key == pg.K_LEFT:
rotate_speed = 5
if event.key == pg.K_RIGHT:
rotate_speed = -5
if event.type == pg.KEYUP:
if event.key == pg.K_LEFT or event.key == pg.K_RIGHT:
rotate_speed = 0
car_rotation = car_rotation + rotate_speed
x = x - forward_movement_x(car_rotation, car_speed, x)
y = y - forward_movement_y(car_rotation, car_speed, y)
x = int(x)
y = int(y)
car_to_space(x, y)
draw_car(x, y)
pg.display.update()
clock.tick(30)
game_loop()
pg.quit()
quit()