I'm trying to create a laser beam for my starship, this laser beam is a drawn rect and not an image, I move the starship with "w-a-s-d" and aim with the mouse, I created a class "Laser" and I've managed to make it aim in the same direction as the player. In addition to rotating, the beam should also move to stay attached to the ship, but I can not understand how to do it.
class Player:
#inizialize the player
def __init__(self, x, y, player):
self.x = x
self.y = y
self.image = player
self.is_shooting = False
self.original_player_image = player
self.angle = 0
#move the player
def movePlayer(self):
if key[0]:
self.x -= 10
elif key[1]:
self.x += 10
if key[2]:
self.y -= 10
elif key[3]:
self.y += 10
#check borders
if self.x <= 0:
self.x = 0
if self.x + rock_image.get_width() >= display_width:
self.x = display_width - player_image.get_width()
if self.y <= 0:
self.y = 0
if self.y + player_image.get_height() >= display_height:
self.y = display_height - player_image.get_height()
#rotate the player where the mouse is aiming
def rotate(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - self.x, mouse_y - self.y
self.angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) - 90
self.image = pygame.transform.rotate(self.original_player_image, int(self.angle))
self.rect = self.image.get_rect()
#draw the player
def drawPlayer(self):
screen.blit(self.image, (self.x, self.y))
class Laser:
def __init__(self, player_x, player_y):
self.x = player_x
self.y = player_y
self.original_image = pygame.Surface((5, 150))
self.original_image.set_colorkey( (0,0,0) )
self.original_image.fill( (255,0,0) )
self.copy_image = self.original_image.copy()
self.copy_image.set_colorkey( (0,0,0) )
self.rect = self.copy_image.get_rect()
self.rect.center = self.x + player_image.get_width()//2, self.y - 75
self.new_image = pygame.Surface((5, 150))
def continueDrawLaser(self):
if laser_bool:
screen.blit(self.new_image, self.rect)
def rotate(self):
mouse_x, mouse_y = pygame.mouse.get_pos()
rel_x, rel_y = mouse_x - player1.x, mouse_y - player1.y
angle = (180 / math.pi) * -math.atan2(rel_y, rel_x) - 85
vel_x = math.cos(angle)
vel_y = math.sin(angle)
self.new_image = pygame.transform.rotate(self.original_image, angle)
self.rect = self.new_image.get_rect()
self.rect.center = player1.x + vel_x, player1.y + vel_y
First there is the Player class(starship) The second one is the Laser class(laser beam)
This is what I get:
If you need the whole code I posted it here:
To let you test the code I have eliminated all the useless things and left only the player with the laser beam, so you have to download only the spaceship to test the code,here the shortened code:
Link to download the spaceship:
https://www.flaticon.com/free-icon/spaceship_1114780?term=space%20ship&page=1&position=57