All the bullets are moving when I move the mouse instead of just the one being shot

Viewed 72

I am trying to make a basic top-down shooter game using Pygame. I just figured out how to make bullets shoot at where my mouse is, but my issue now is they will shift direction whenever I move my mouse even after being shot. Additionally, when the bullets collide with the left edge of the screen they do not disappear like with the other edges.

main.py:

import pygame
import time
import math
import os
import sys
import random
from classes import *

pygame.init()

width, height = (1440, 900)
win = pygame.display.set_mode((width, height), pygame.FULLSCREEN)
pygame.display.set_caption("Dungeon")
win.fill((255, 255, 255))

# Variables to do with player shooting
shotTimer = 0
bullets = []
bulletVel = 9

# Initialize classes
player = Player(50, 800, 50, 50, PLAYERSPRITE)

def main():
    run = True
    FPS = 60
    clock = pygame.time.Clock()



    while run:
        clock.tick(FPS)

        now = pygame.time.get_ticks()

        mousex, mousey = pygame.mouse.get_pos()

        # Creates the player's bullets
        def shoot():
            global shotTimer

            if now - shotTimer >= player.cooldown:
                bullets.append(Projectile(round(player.x + player.width // 2), round(player.y + player.height // 2), 6))
                shotTimer = now

        def playerBulletUpdates():
            for bullet in bullets:
                if bullet.x >= 0 and bullet.x <= width:
                    if bullet.y >= 0 and bullet.y <= height:
                        global bulletVel

                        xDiff = mousex - player.x
                        yDiff = mousey - player.y

                        angle = math.atan2(yDiff, xDiff)

                        changeX = math.cos(angle) * bulletVel
                        changeY = math.sin(angle) * bulletVel

                        bullet.x += changeX
                        bullet.y += changeY
                    else:
                        bullets.pop(bullets.index(bullet))

        def bulletAngle():
            global bulletVel

            xDiff = mousex - player.x
            yDiff = mousey - player.y

            angle = math.atan2(yDiff, xDiff)

            changeX = int(math.cos(angle) * bulletVel)
            changeY = int(math.sin(angle) * bulletVel)

            bullet.x += changeX
            bullet.y += changeY

        def updateScreen():
            win.fill((255, 255, 255))
            player.draw(win)

            for bullet in bullets:
                bullet.draw(win)

            playerBulletUpdates()

            pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys = pygame.key.get_pressed()

        if keys[pygame.K_w] and player.y  >= 0: # UP
            player.y += -player.walkSpeed

        if keys[pygame.K_s] and player.y + player.walkSpeed + player.height <= height: # DOWN
            player.y += player.walkSpeed

        if keys[pygame.K_a] and player.x >= 0: #LEFT
            player.x += -player.walkSpeed

        if keys[pygame.K_d] and player.x + player.walkSpeed + player.width <= width: # RIGHT
            player.x += player.walkSpeed

        if pygame.mouse.get_pressed()[0]:
            shoot()

        updateScreen()

main()

classes.py:

import pygame
import math
import os

pygame.init()

width, height = (1440, 900)
win = pygame.display.set_mode((width, height), pygame.FULLSCREEN)

# Import Sprites
PLAYERSPRITE = pygame.image.load(os.path.join("assets", "gunner_class.png"))
BULLETSPRITE = pygame.image.load(os.path.join("assets", "bullet.png"))

class Player:
    def __init__(self, x, y, width, height, img):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.img = img
        self.walkSpeed = 5
        self.cooldown = 100

    def draw(self, window):
        window.blit(PLAYERSPRITE, (self.x, self.y))

class Projectile:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius

    def draw(self, window):
            # pygame.draw.circle(window, self.color, (self.x, self.y), self.radius)
            window.blit(BULLETSPRITE, (self.x, self.y))
1 Answers

The bullets not being deleted when they pass x=0, simply because you don't cull them on "bad-x", as the "else pop" clause is only called on "bad-y". It's easy to fix:

    def playerBulletUpdates():
        for bullet in bullets:
            if bullet.x >= 0 and bullet.x <= width and \
               bullet.y >= 0 and bullet.y <= height:
                    ...
            else:
                # Bullet has gone off-screen
                bullets.pop(bullets.index(bullet))  

The mouse-movement of existing bullets is because, during this same loop, you re-compute the direction vectors for every bullet, not just the new one.

Your Projectile class needs to store its direction vector during initialisation - one for every bullet, as it is probably different for every bullet. So I would re-work the constructor here, then add an update() function to handle the continued movement.

class Projectile:
    def __init__(self, x, y, dx, dy, radius):
        self.x      = x
        self.y      = y
        self.radius = radius
        self.dx     = dx
        self.dy     = dy

    def draw(self, window):
        # pygame.draw.circle(window, self.color, (self.x, self.y), self.radius)
        window.blit(BULLETSPRITE, (self.x, self.y))

    def update( self ):
        """ Move the projectile along its path """
        self.x += self.dx
        self.y += self.dy

shoot() now calculates the direction vecotor ~

def shoot( mousex, mousey, player ):
    """ Creates a player's bullets """
    global shotTimer

    if now - shotTimer >= player.cooldown:
        global bulletVel

        xDiff = mousex - player.x
        yDiff = mousey - player.y
        angle = math.atan2(yDiff, xDiff)

        # Direction of travel
        changeX = math.cos(angle) * bulletVel
        changeY = math.sin(angle) * bulletVel

        # Start position
        new_bullet_x = round(player.x + player.width / 2)
        new_bulley_y = round(player.y + player.height / 2)

        bullets.append( Projectile( new_bullet_x, new_bulley_y, changeX, changeY, 6))
        shotTimer = now

Making the bullet update function much simpler too:

def playerBulletUpdates():
    for bullet in bullets:
        if bullet.x >= 0 and bullet.x <= width and bullet.y >= 0 and bullet.y <= height:
            # Move the bullet
            bullet.update()
        else:
            # Bullet has gone off-screen
            bullets.pop(bullets.index(bullet))

While you're changing these things around. It might be worthwhile investigating PyGame Rect objects using their positioning rather than discrete x and y, as that would give access to the excellent collision functions.

Related