I am trying to create a top-down game in pygame. One of the features is a gun which should point towards the mouse. The first two code snippets below worked perfectly before I implemented the camera with the third snippet.
def angle_to_mouse(self):
mouse_pos = vec(pygame.mouse.get_pos())
gun_pos = vec(self.rect.center)
dx = mouse_pos.x - gun_pos.x
dy = -(mouse_pos.y - gun_pos.y)
if dx != 0:
return math.degrees(math.atan2(dy, dx))
self.image = pygame.transform.rotate(self.base_image, self.angle_to_mouse())
Once I had added the camera the gun started exhibiting strange behavior. If the mouse was ever close to the gun the gun would be stuck and loop between 0 and three degrees.
class CameraGroup(pygame.sprite.Group):
def __init__(self, target=None, *sprites):
super().__init__(*sprites)
self.target = target
self.offsetx = 0
self.offsety = 0
def get_offset(self):
self.offsetx = WIDTH / 2 - self.target.rect.x
self.offsety = HEIGHT / 2 - self.target.rect.y
return vec(self.offsetx, self.offsety)
def camera_draw(self, screen):
self.get_offset()
for sprite in self.sprites():
offset_pos = (
round(sprite.rect.x + self.offsetx),
round(sprite.rect.y + self.offsety),
)
screen.blit(sprite.image, offset_pos)
def set_target(self, sprite):
self.target = sprite
At first I assumed it was something to do with radians and made sure I converted my angle to degrees. Then I tried subtracting the offset of the camera to gun_pos
in the angle_to_mouse
method. I did this to try to obtain the “true” position of the gun before the camera changes anything. However the problem persisted.
Any help would be appreciated. Thanks in advance.
Github Project
I_Use_Python is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.