我一直在尝试为我正在制作的游戏(基于疯狂上帝的境界)实现一项功能,您可以在其中点击即可射击。为了做到这一点,我一直在尝试使用毕达哥拉斯和三角形的上升或梯度规则来计算 x 和 y 每次必须移动多远才能保持稳定的步伐,并在每次点击时保持该步伐。在我所看到的所有地方,人们一直在使用角度和 python 2,而我目前正在使用 python 3,因此使代码兼容比仅仅询问更棘手。我的代码使用类来创建障碍物和纹理。我正在使用数组来存储和创建游戏循环内的子弹,并使用 pygames 矩形功能将它们绘制到屏幕上。请参阅下面的代码(不包括所有代码)。
import pygame, random, time
pygame.init()
shoot= []
class Projectiles(object):
def __init__(self, pos):
self.rect = pygame.Rect(pos[0], pos[1], 20, 20)
shoot.append(self)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
quit()
if event.key == pygame.K_a:
movement_status = pcharl
x_change = 5
if event.key == pygame.K_w:
movement_status = pcharb
y_change = 5
if event.key == pygame.K_s:
movement_status = pchar
y_change = -5
if event.key == pygame.K_d:
movement_status = pcharr
x_change = -5
if event.key == pygame.K_e:
pygame.display.toggle_fullscreen()
if event.key == pygame.K_SPACE:
shooting = True
if movement_status == pcharl:
Projectiles((x, y))
direction = "left"
bx_change = -8
shooting = True
if movement_status == pcharr:
Projectiles((x+30, y))
direction = "right"
bx_change = 8
shooting = True
if movement_status == pcharb:
Projectiles((x + 30, y))
direction = "up"
by_change = -8
shooting = True
if movement_status == pchar:
Projectiles((x + 30, y))
direction = "down"
by_change = 8
shooting = True
if event.type == pygame.KEYUP:
x_change = 0
y_change = 0
if event.type == pygame.MOUSEBUTTONDOWN:
xm,ym = pygame.mouse.get_pos()
shooting_arr = True
if movement_status == pchar:
Projectiles((x + 60, y))
bullx = 560
if movement_status == pcharb:
Projectiles((x + 60, y))
bullx = 560
if movement_status == pcharr:
Projectiles((x + 60, y))
bullx = 560
if movement_status == pcharl:
Projectiles((x, y))
bullx = 500
for bullet in shoot:
pygame.draw.rect(screen, (255, 100, 0), bullet.rect)
xm = xm - bullx
ym = ym - 500
if xm % 2 == 0 and ym % 2 == 0:
xm = xm / 2
ym = ym / 2
xm = xm / ym
ym = ym / xm
bx_change = xm
by_change = ym
print(str(xm) + " " + str(ym))
xm = 0
ym = 0
shooting = True
screen.fill((225, 50, 25))
if shooting:
for bullet in shoot:
pygame.draw.rect(screen, (255, 0, 255), bullet.rect)
bullet.rect.x += bx_change
bullet.rect.y += by_change
if bullet.rect.x <= 0:
shoot.remove(bullet)
if bullet.rect.x >= 1000:
shoot.remove(bullet)
if bullet.rect.y <= 0:
shoot.remove(bullet)
if bullet.rect.y >= 1000:
shoot.remove(bullet)
x 和 y 等于 500 屏幕尺寸为 1000x1000