我想让我的子弹沿着我的船的方向射击。我设法利用这个非常有用的代码在游戏中的子弹:How to create bullets in pygame?在我的船指向的方向上射击子弹
让我参考提供一些代码。下面是一组用于旋转我的船的代码,以及让它沿着这个方向移动。另外,Offset = 0
。
'''Directional commands for the sprite'''
if pressed[pygame.K_LEFT]: offset_change += 4
if pressed[pygame.K_RIGHT]: offset_change -= 4
if pressed[pygame.K_UP]:
y_change -= cos(spaceship.angle) * 8
x_change -= sin(spaceship.angle) * 8
if pressed[pygame.K_DOWN]:
y_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
x_change = 0
y_change = 0
offset_change = 0
'''changes X/Y based on the value of X/Y_Change'''
spaceship.angle += offset_change
spaceship.startY += y_change
spaceship.startX += x_change
下面是类的飞船代码是英寸
class Spaceship():
'''Class attributed to loading the spaceship'''
def __init__(self, char, startX, startY, Angle):
'''Loads in the image and sets variables'''
self.char = char
self.startX = startX
self.startY = startY
self.angle = Angle
self.space = load_item(self.char)
self.drawChar()
def drawChar(self):
'''Draws the image on the screen'''
#Code is from Pygame documentation
#Due to limitations of Pygame the following code had to be used with a few of my own manipulations
rot_image = pygame.transform.rotate(self.space,self.angle)
rot_rect = self.space.get_rect()
rot_rect.center = rot_image.get_rect().center
rot_image = rot_image.subsurface(rot_rect).copy()
gameDisplay.blit(rot_image,(self.startX,self.startY))
现在的“如何创建子弹......”链接我前面提到的,我想换
的一部分for b in range(len(bullets)):
bullets[b][1] -= 8
到bullets[spaceship.startX][spaceship.startY] -= 8
由于这是我的信念,该行代码来表示bullets[x][y]
。然而我被提出了TypeError: list indices must be integers, not float
。
我猜我的假设是错误的。你可以建议让我的子弹按照我喜欢的方式移动吗?
请考虑寻找到PEP008(蟒蛇风格
如下,角度和速度来改变自己的价值观,您可以更新他们指南)。和一个小技巧:不用重复'==',你可以在[pygame.K_RIGHT,pygame.K_LEFT,...]中使用'event.key'。 – CodenameLambda
@CodingLambdas我不知道我在找什么在这里.. – Lucky38i
我正在写一个答案,包括一个PointMass类,这是一个简单的物理模拟,但我觉得它会太多。这就是为什么下面只有一个简单的答案。在我以前的评论中的东西只是让你的代码更具可读性的提示。 – CodenameLambda