import pygame
import os
import math
import sys
pygame.init()
WIDTH = 900
HEIGHT = 660
FPS = 60
VEL = 2`your text`
CHARACTER_WIDTH = 50
CHARACTER_HEIGHT = 50
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("STRANDED LOST")
BACKGROUND = pygame.image.load(os.path.join('textures', 'background.png'))
BACKGROUND = pygame.transform.scale(BACKGROUND, (WIDTH, HEIGHT))
CHARACTER = pygame.image.load(os.path.join('textures', 'character.png'))
CHARACTER = pygame.transform.scale(
CHARACTER, (CHARACTER_WIDTH, CHARACTER_HEIGHT))
CROSSHAIR = pygame.image.load(os.path.join('textures', 'crosshair.png'))
CROSSHAIR = pygame.transform.scale(CROSSHAIR, (25, 25))
playerCharacter = pygame.Rect(
WIDTH // 2, HEIGHT // 2, CHARACTER_WIDTH, CHARACTER_HEIGHT)
pygame.mouse.set_visible(False)
def draw_window(playerCharacter, crosshair_pos):
screen.blit(BACKGROUND, (0, 0))
screen.blit(CROSSHAIR, crosshair_pos)
screen.blit(CHARACTER, playerCharacter)
def game():
clock = pygame.time.Clock()
running = True
while running:
# framerate
clock.tick(FPS)
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# key control
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_a]: # LEFT
playerCharacter.x -= VEL
if keys_pressed[pygame.K_d]: # RIGHT
playerCharacter.x += VEL
if keys_pressed[pygame.K_w]: # UP
playerCharacter.y -= VEL
if keys_pressed[pygame.K_s]: # DOWN
playerCharacter.y += VEL
# get mouse position
mouse_pos = pygame.mouse.get_pos()
# crosshair positionm
crosshair_pos = (mouse_pos[0] - CROSSHAIR.get_width() / 2,
mouse_pos[1] - CROSSHAIR.get_height() / 2)
# character rotation
angle = math.atan2(
mouse_pos[1] - (playerCharacter[1]+32), mouse_pos[0] - (playerCharacter[0]+26))
rotate = pygame.transform.rotate(CHARACTER, 360 - angle * 57.29)
playerposnew = (playerCharacter[0] - rotate.get_rect().width/2,
playerCharacter[1] - rotate.get_rect().height/2)
screen.blit(rotate, playerposnew)
draw_window(playerCharacter, crosshair_pos)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
game()
Please help me understand why my character is not rotating towards my mouse pointer. I have tried different equations to calculate the angle, however I think that the problem is with when the character is being drawn also I don't understand whether the character image would rotate if the rectangle is rotate and the image is being drawn onto it or I need to draw a rotating image onto a rectangle?
I tried to make my CHARACTER image and rectangle rotate towards my mouse pointer, I've been trying for hours and nothing works, please help me :)