I have fixed the problem pointed out in this post, but now I am confused on how to point the gray rectangle (barrel) towards my mouse. Could somebody please help? Thanks!
Here is my code:
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("diep.io")
screen.fill((255,255,255))
auto_shoot = False
class Bullet:
def __init__(self, x_move, y_move, x_loc, y_loc):
self.image = pygame.image.load("C:\\Users\\ender\\OneDrive\\Documents\\repos\\Bullet.png")
self.x_move = x_move
self.y_move = y_move
self.x_loc = x_loc
self.y_loc = y_loc
self.bullet_rect = self.image.get_rect()
def update(self):
self.x_loc += self.x_move
self.y_loc += self.y_move
self.bullet_rect.center = round(self.x_loc), round(self.y_loc)
rect = screen.blit(self.image, self.bullet_rect)
if not screen.get_rect().contains(rect):
bullets.remove(self)
if self.x_loc > 400 or self.y_loc > 400:
bullets.remove(self)
bullet = None
bullets = []
while True:
screen.fill((255, 255, 255))
pygame.draw.rect(screen, (100, 100, 100), (205, 193, 25, 15)) # This is the rectangle I want to point at my mouse
pygame.draw.circle(screen, (82, 219, 255), (200, 200), 15)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP:
x = pygame.mouse.get_pos()[0] - 200
y = pygame.mouse.get_pos()[1] - 200
pythag = float(math.sqrt(x**2 + y**2))
bullets.append(Bullet(x/pythag, y/pythag, 200, 200))
for bullet in bullets:
bullet.update()
pygame.display.update()
pygame.time.delay(10)
Note: This is different from other problems because I am trying to point a rectangle at my mouse, and other posts are pointing an image at the mouse. That is not what I want to do. Secondly, pygame rectangles are defined by their bottom left corner, so this further complicates things.