3
votes

I've finally figured out how to shoot bullets but now I want to rotate the origin of the bullets on the rotation of the players head. Now it's only shooting straight on the x line. The mobs are working fine. I only need to add in collision and the bullet that is rotating on the player's angle. I will do the collision myself although If anyone could hint me it would be appreciated. My main focus right now is to rotate the bullet according to the player's angle and 'kill' the bullet when it flies off screen.

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()

So It needs to rotate on the players self.angle which is updated when pressing key up or key down.

1
what is your question ?Stephane Martin
To let the bullet rotate to the rotation of the player's position and angle. It only shoots straight lines on the X-as right now.Ectrizz
Do you have experience with trigonometry or vectors?skrx
nope. I have little knowledge about pygame that's why I was asking. I know what the codes do and mean in the current state.Ectrizz
Take a look at this answer. You have to learn how trigonometry or vectors work to understand it (khanacademy.org is a good resource).skrx

1 Answers

2
votes

You need to use trigonometry or vectors to calculate the velocity of the bullet (I use trig here). Pass the angle of the player to the Bullet and then use math.cos and math.sin with the negative angle to get the direction of the bullet and scale it by the desired speed. The actual position has to be stored in a list or vector, because pygame.Rects can only have ints as their coordinates.

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)