Me and a few friends have been coding an intresting new shooting mechanic. For It to work, we need to shoot in the direction the player is facing. The Sprite is being rotated with Pygame.Transform.Rotate. How can we get an angle, and shoot our bullet in that direction?
Here is Our Code for rotation of the Sprite
char_image_number = pygame.mouse.get_pressed()
if char_image_number == (0, 0, 0):
char_image = pygame.image.load(player_none).convert_alpha()
char_image = pygame.transform.rotate(char_image, angle)
screen.blit(background, (0,0))
screen.blit(char_image,(540, 260))
pygame.display.update()
elif char_image_number == (1, 0, 0):
print (angle)
char_image = pygame.image.load(player_left).convert_alpha()
angle+=1
char_image = pygame.transform.rotate(char_image, angle)
screen.blit(background, (0,0))
screen.blit(char_image,(540, 260))
pygame.display.update()
elif char_image_number == (0, 0, 1):
print (angle)
angle-=1
char_image = pygame.image.load(player_right).convert_alpha()
char_image=pygame.transform.rotate(char_image, angle)
screen.blit(background, (0,0))
screen.blit(char_image,(540, 260))
pygame.display.update()
elif char_image_number == (1, 0, 1):
char_image = pygame.image.load(player_both).convert_alpha()
char_image = pygame.transform.rotate(char_image, angle)
screen.blit(background, (0,0))
screen.blit(char_image,(540, 260))
pygame.display.update()
How can we shoot at the angle the player is facing?
You have
angle
in degrees so try this:Now you can add
bullet_move_x
,bullet_move_y
to bullet positon.For better results keep bullet position as
float
and convert toint
when you blit bulletHere's a quick'n'dirty executable example of how to use vector math to do what you want.
Note: it seems that you're loading the image of your player every frame. You should not do that, as this is very slow. Just load each image once. Also, it's better to have only one spot in your code that calls
pygame.display.update()
, as you should make sure it's called only once each frame.This example demonstrates how vectors can be utilized to control the position, velocity and also the start offset of the bullets.
In the while loop we use
math.atan2
to calculate the angle to the target which is then used to rotate the cannon image and passed to theBullet
instances. In the__init__
method of theBullet
s we rotate the offset vector, velocity vector and the sprite image by the angle.To move the bullet, we add the (rotated) velocity vector to the position vector and set the rect position to the
pos
vector. The rect has to be moved, because it holds the blit position and is used for collision detection.