so I tried to add the weapon to my game and rotate it on a pivot point looking to the mouse, I achieved to do it but I have an issue I can't resolve, when I walk with my player, after I walk down around the middle of the map the rotate angle looks to become wrong.
I link you a gif for a better understanding.
Here is some part of the working rotation code :
import pygame, os, math
from weapon_constants import *
from level_constants import *
from pygame.math import Vector2
class Weapon(pygame.sprite.Sprite):
def __init__(self, game, name, label, x, y):
self._layer = WEAPON_LAYER
self.groups = game.all_sprites, game.weapons
pygame.sprite.Sprite.__init__(self, self.groups)
self.options = WEAPONS[name]
self.label = label
self.game = game
self.file = os.path.join(os.getcwd(), DEFAULT_WEAPON_IMAGE_PATH, self.get_option('image'))
self.image = pygame.transform.scale(pygame.image.load(self.file).convert_alpha(), DEFAULT_WEAPON_SIZE)
self.original_image = self.image
self.rect = self.image.get_rect(center=(x, y))
self.offset = Vector2(25, 0)
self.pos = Vector2(self.rect.x, self.rect.y)
self.angle = 0
def get_option(self, option):
if option in self.options:
return self.options[option]
return False
def update(self):
self.pos = Vector2(self.game.player.rect.center)
rel_x, rel_y = pygame.mouse.get_pos() - self.pos
self.angle = (180 / math.pi) * math.atan2(rel_y, rel_x)
if self.pos.y > pygame.display.get_surface().get_width() // 2:
print('bad rotation happen \n pos_y : {}, \n angle : {}, \n mouse_pos : {}'.format(self.pos.y, self.angle, pygame.mouse.get_pos()))
pass
self.rotate()
def rotate(self):
self.image = pygame.transform.rotozoom(self.original_image, -self.angle, 1)
rotated_offset = self.offset.rotate(self.angle)
self.rect = self.image.get_rect(center= self.pos + rotated_offset)
Here is the first output (I saw it was around half width of the map) :
bad rotation happen
pos_y : 452.0,
angle : 23.962488974578186,
mouse_pos : (450, 468)