【问题标题】:how to rotate a bullet according to the player's rotation如何根据玩家的旋转来旋转子弹
【发布时间】:2018-05-26 01:31:38
【问题描述】:

我终于想出了如何射击子弹,但现在我想在玩家头部旋转时旋转子弹的原点。现在它只在 x 线上直线射击。暴徒工作正常。我只需要添加碰撞和按玩家角度旋转的子弹。我会自己做碰撞,但如果有人能暗示我,我将不胜感激。我现在主要关注的是根据玩家的角度旋转子弹并在子弹飞出屏幕时“杀死”子弹。

import pygame
import random
import math
GRAD = math.pi / 180

black = (0,0,0)

class Config(object):
    fullscreen = True
    width = 1366
    height = 768
    fps = 60

class Player(pygame.sprite.Sprite): #player class
    maxrotate = 180
    down = (pygame.K_DOWN)
    up = (pygame.K_UP)

    def __init__(self, startpos=(102,579), angle=0):
        super().__init__()
        self.pos = list(startpos)
        self.image = pygame.image.load('BigShagHoofdzzz.gif')
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=startpos)
        self.angle = angle

    def update(self, seconds):
        pressedkeys = pygame.key.get_pressed()
        if pressedkeys[self.down]:
            self.angle -= 2
            self.rotate_image()
        if pressedkeys[self.up]:
            self.angle += 2
            self.rotate_image()

    def rotate_image(self):#rotating player image
        self.image = pygame.transform.rotate(self.orig_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

class Mob(pygame.sprite.Sprite):#monster sprite
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load('Monster1re.png')
        self.rect = self.image.get_rect()
        self.rect.x = 1400
        self.rect.y = random.randrange(500,600)
        self.speedy = random.randrange(-8, -1)

    def update(self):
        self.rect.x += self.speedy
        if self.rect.x < -100 :
            self.rect.x = 1400
            self.speedy = random.randrange(-8, -1)

class Bullet(pygame.sprite.Sprite):#bullet sprite needs to rotate according to player's angle. 
    """ This class represents the bullet . """
    def __init__(self):
        # Call the parent class (Sprite) constructor
        super().__init__()

        self.image = pygame.image.load('lols.png').convert()
        self.image.set_colorkey(black)
        self.rect = self.image.get_rect()

    def update(self):
        """ Move the bullet. """
        self.rect.x += 10



#end class

player = Player()

mobs = []
for x in range(0,10):
    mob = Mob()
    mobs.append(mob)

print(mobs)

all_sprites_list = pygame.sprite.Group()
allgroup = pygame.sprite.LayeredUpdates()
allgroup.add(player)

for mob in mobs:
    all_sprites_list.add(mob)








def main():
    #game 
    pygame.mixer.pre_init(44100, -16, 1, 512)
    pygame.mixer.init()
    pygame.init()
    screen=pygame.display.set_mode((Config.width, Config.height),         
    pygame.FULLSCREEN)
    background = pygame.image.load('BGGameBig.png')
    sound = pygame.mixer.Sound("shoot2.wav")
    bullet_list = pygame.sprite.Group

    clock = pygame.time.Clock()
    FPS = Config.fps


    mainloop = True
    while mainloop:
        millisecond = clock.tick(Config.fps)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    mainloop = False
                if event.key == pygame.K_SPACE: #Bullet schiet knop op space
                    bullet = Bullet()
                    bullet.rect.x = player.rect.x
                    bullet.rect.y = player.rect.y
                    all_sprites_list.add(bullet)
                    bullet_list.add(bullet)
                    sound.play()
                if event.key == pygame.K_ESCAPE:
                    mailoop = False 


        pygame.display.set_caption("hi")
        allgroup.update(millisecond)
        all_sprites_list.update()
        screen.blit(background, (0,0))
        allgroup.draw(screen)
        all_sprites_list.draw(screen)
        pygame.display.flip()


if __name__ == '__main__':
    main()
    pygame.quit()

所以它需要在玩家 self.angle 上旋转,当按下 key up 或 key down 时更新。

【问题讨论】:

  • 你的问题是什么?
  • 让子弹旋转到玩家的位置和角度的旋转。它现在只能在 X-as 上拍摄直线。
  • 您有使用三角函数或向量的经验吗?
  • 不。我对pygame知之甚少,这就是我问的原因。我知道代码在当前状态下的作用和含义。
  • 看看this answer。您必须学习三角函数或向量的工作原理才能理解它(khanacademy.org 是一个很好的资源)。

标签: python rotation pygame bullet


【解决方案1】:

您需要使用三角函数或向量来计算子弹的速度(我在这里使用三角函数)。将玩家的角度传递给Bullet,然后使用带有负角度的math.cosmath.sin 来获取子弹的方向并按所需速度对其进行缩放。实际位置必须存储在列表或向量中,因为pygame.Rects 只能以整数作为坐标。

class Bullet(pygame.sprite.Sprite): 
    """This class represents the bullet."""
    def __init__(self, pos, angle):
        super().__init__()
        # Rotate the image.
        self.image = pygame.transform.rotate(your_bullet_image, angle)
        self.rect = self.image.get_rect()
        speed = 5  # 5 pixels per frame.
        # Use trigonometry to calculate the velocity.
        self.velocity_x = math.cos(math.radians(-angle)) * speed
        self.velocity_y = math.sin(math.radians(-angle)) * speed
        # Store the actual position in a list or a vector.
        self.pos = list(pos)

    def update(self):
        """ Move the bullet. """
        self.pos[0] += self.velocity_x
        self.pos[1] += self.velocity_y
        # Update the position of the rect as well.
        self.rect.center = self.pos


# In the event loop.
if event.key == pygame.K_SPACE:
    # Pass the position and angle of the player.
    bullet = Bullet(player.rect.center, player.angle)
    all_sprites_list.add(bullet)
    bullet_list.add(bullet)

【讨论】:

  • 啊,我明白了。不过,我不得不再添加一行代码。使用该代码时出现错误。我添加了代码:self.image = pygame.image.load('mypicture')。因为它给我一个关于 pygame.surface 的错误,而不是 str。但是现在效果很好!谢谢!现在我将继续讨论碰撞:P 希望我能解决这个问题
  • 不要在__init__方法中加载图片,因为在创建实例的时候需要一次次从硬盘加载,速度很慢。在全局范围或另一个模块中加载图像并导入它,然后在程序中重用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多