I'm making a simple topdown shooter game. The problem is with bullet starting point. I have player image where rifle barrel is between topmid and topright of rectangle. How to make bullet start always from the rifle barrel regardless image rotation?
# key input
def get_input(self, dt):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.direction.rotate_ip(dt * -360)
if keys[pygame.K_RIGHT]:
self.direction.rotate_ip(dt * 360)
self.angle = self.direction.angle_to((0, -1))
self.image = pygame.transform.rotate(self.image, self.angle)
self.rect = self.image.get_rect(center=self.rect.center)
if keys[pygame.K_UP]:
self.movement = 1
self.status = 'move'
else:
self.movement = 0
self.status = 'idle'
if keys[pygame.K_DOWN]:
self.movement = -1
self.status = 'move'
if keys[pygame.K_SPACE] and not self.bullet.sprites():
self.create_bullet(dt)
shoot = pygame.mixer.Sound('audio/rumble.flac')
shoot.play()
# movement
def move(self, speed, dt):
movement_v = self.direction * self.movement
if movement_v.length() > 0:
movement_v.normalize_ip()
self.pos += movement_v * dt * speed
self.rect = self.image.get_rect(center=self.pos)
# boundary
if self.rect.x <= 0:
self.rect.x = 0
if self.rect.x >= 1216:
self.rect.x = 1216
if self.rect.y <= 0:
self.rect.y = 0
if self.rect.y >= 704:
self.rect.y = 704
# create bullet instance
def create_bullet(self, dt):
self.bullet.add(Bullet(self.rect.center, self.direction.normalize(), self.bullet_speed, self.angle))
You have rotate the offset of the bullet starting point with pygame.math.Vector2.rotate
. e.g.:
offset = pygame.math.Vecotr2(15, 10) # (15, 10) is just an example
rotated_offset = offset.rotate(-self.angle)
pos = pygame.math.Vector2(self.rect.center) + rotated_offset
bullet = Bullet((pos.x, pos.y), ...)