My bullet won't move towards the location I click on for example I click on the left side of the screen and it will move to the bottom left corner of the screen. I believe it has something to do with the angle at which the bullet is sent however I'm not sure.
import pygame
from pygame.locals import *
import time
import math
pygame.init()
Below I set up the bullet class holding the details about the bullet
class bullet:
bullet_img = pygame.image.load("bullet png for game.png")
bullet_img = pygame.transform.scale(bullet_img,(70,60))
bullet_dx = 2
bullet_dy = 2
bullet_x = 450
bullet_y = 450
bullet_travelling = False
player_bullet = bullet
Setting up window
screen_width = 1000
screen_height = 1000
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Shooting Prototype")
# functions
Gets the position of the mouse and returns it def get_cords(): mouse_x,mouse_y = pygame.mouse.get_pos() return mouse_x,mouse_y
Gets the distance between the current position of the bullet and the mouse position
def get_distance(mouse_x,mouse_y):
x_distance = mouse_x - player_bullet.bullet_x
y_distance = mouse_y - player_bullet.bullet_y
print("distance",x_distance,y_distance)
return x_distance,y_distance
Calculates the angle for the bullet to move
def calculate_angle(x_distance,y_distance):
distance_over_distance = y_distance/x_distance
angle = math.atan(distance_over_distance)
print(angle)
return angle
Finds the speeds for the bullet to move at
def calculate_dy_and_dx():
player_bullet.bullet_dx = math.cos(angle)*5
player_bullet.bullet_dx = math.sin(angle)*5
player_bullet.bullet_travelling = True
moves the bullet if the bullet hits the borders the bullet stops
def move_bullet():
if player_bullet.bullet_x <= 0 or player_bullet.bullet_x >= 1000 or player_bullet.bullet_y <= 0 or player_bullet.bullet_y >= 1000:
player_bullet.bullet_travelling = False
if player_bullet.bullet_x >= 0 or player_bullet.bullet_x <= 1000 or player_bullet.bullet_y >= 0 or player_bullet.bullet_y <= 1000:
player_bullet.bullet_x += player_bullet.bullet_dx
print("position x",player_bullet.bullet_x)
player_bullet.bullet_y += player_bullet.bullet_dy
print("position y",player_bullet.bullet_y)
background_img = pygame.image.load("industrial background.png")
run = True
# game loop
while run:
screen.blit(background_img, (0,0))
screen.blit(player_bullet.bullet_img, (player_bullet.bullet_x,player_bullet.bullet_y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
mouse_x,mouse_y = get_cords()
x_distance,y_distance = get_distance(mouse_x,mouse_y)
angle = calculate_angle(x_distance,y_distance)
calculate_dy_and_dx()
if player_bullet.bullet_travelling == True:
move_bullet()
pygame.display.update()
pygame.quit()