I was working on a game in pygame and I wanted to create a bullet that could rotate it's image based on the angle of its pygame vector . Originally I wanted to do it with the vector that would be added to its position that gets calculated upon its initiation that makes the bullet travel to the mouse on screen. However I realized the only built in way to get angles from vectors was to use the pygame.Vector2.angle_to()
method.
I decided I would do this just by creating the angle before the bullet was initialized then pass it through and then use the pygame.transform.rotate(bulletImage, -angle)
(I computed this with the player's position on screen and the mouse click position). However when I did this the angle just didn't seemed to work and be all over the place. I will include the code for what happens on fire and how the bullet becomes initiated. I checked the variables going in but I couldn't get it to produce a good angle; It returned a relatively low angle that was always off.
My question is just whether there is a way to get a bullet image to rotate through its movement vectors or player relative vector or if I need to find another way to do this.
Gun checkFire script:
def checkFire(self):
for event in self.game.events:
if event.type == pygame.MOUSEBUTTONUP: ## Checks on click release
mPos = pygame.Vector2(pygame.mouse.get_pos()) ## Gets mouse position and stores it in vector. This will be translated into the vector that moves the bullet
pPos = self.game.cam.apply(self.player) ## Gets actual position of player on screen
pPosVec = pygame.Vector2((pPos.x, pPos.y))
angle = pPosVec.angle_to(mPos) ## Gets angle between player vector and mouse vector
mPos.x -= pPos.centerx ## Finds the x and y relativity between the mouse and player and then calculates the offset
mPos.y -= pPos.centery
bullet(self.game, self.rect.center, mPos, angle) ## Inputs values.
self.lastFire = pygame.time.get_ticks()
I have a camera set up in the game object that keeps the player within the tilemap and makes it scroll so I had to use that function to get the player's absolute coordinates which when tested were perfectly fine. The problem should be somewhere in here.
Bullet Script
class bullet(pygame.sprite.Sprite):
pos = pygame.Vector2((0,0))
image = pygame.image.load(asset('objects/bullet2.png'))
vel = 20
def __init__(self, game, pos, target, angle, **kwargs):
self.groups = game.sprites, game.bullets, game.layer2
pygame.sprite.Sprite.__init__(self, self.groups)
for k, v in kwargs.items():
self.__dict__[k] = v
print(angle)
self.pos = pygame.Vector2(pos)
self.dir = pygame.Vector2(target).normalize()
self.image = pygame.transform.rotate(self.image, angle)
self.rect = pygame.Rect(0, 0, self.image.get_width(), self.image.get_height())
self.rect.center = self.pos
def update(self):
self.pos += self.dir *self.vel
self.rect.center = self.pos
The directional movement of the bullet is perfect just the derivation of the angle is bad.