-3

My picture should point in the direction of my mouse but it doesn't work because I am enlarging my screen (because I make pixel art). I think the coordinates are influenced by the magnifying of my screen

can you help me with fixing that issue??

here is my code:

import pygame
import sys
import random
import math

from pygame.locals import *
pygame.init()

clock = pygame.time.Clock()

screen_width = 1440
screen_height = 900
screen = pygame.display.set_mode((screen_width,screen_height))
display = pygame.Surface((int(1440/2),int(900/2)))

player = pygame.Rect(50,50,50,50)

bow_path = "data/bow_1.png"
bow = pygame.image.load(bow_path).convert()
bow.set_colorkey((255,255,255))

#---movement---#
right = False
left = False
down = False
up = False

movement = [0,0]
while True:
    display.fill((0,0,0))
    press_timer = 0
    mx,my = pygame.mouse.get_pos()

    movement = [0,0]
    if right == True:
        movement[0] += 2.5
        
    if left == True:
        movement[0] -= 2.5
       
    if up == True:
        movement[1] -= 2.5
        
    if down == True:
        movement[1] += 2.5

    player.x += int(movement[0])
    player.y += int(movement[1])

    bow_rect = bow.get_rect()     
    angle = math.degrees(math.atan2(player.centery - my, mx - player.centerx)) + 180
    rotated_bow = pygame.transform.rotate(bow,angle)
    
    pygame.draw.rect(display,(255,255,255),player)
    display.blit(rotated_bow,(int(player.x+25)-int(rotated_bow.get_width()/2),int(player.y+25)-int(rotated_bow.get_height()/2)))

here I change the size of my screen:

    screen.blit(pygame.transform.scale(display,(screen_width,screen_height)),(0,0))
    pygame.display.update()
    clock.tick(60)
Levi
  • 51
  • 5

1 Answers1

1

The mouse coordinates are always relative to the native resolution. When you scale a surface to the screen, you must descale the mouse coordinates to match the surface.

Here is the updated code:

bow_rect = bow.get_rect()
# reverse scale mouse coordinates (1/2x)
angle = math.degrees(math.atan2(player.centery - my/2, mx/2 - player.centerx)) + 180
rotated_bow = pygame.transform.rotate(bow,angle)

pygame.draw.rect(display,(255,255,255),player)
display.blit(rotated_bow, (int(player.x+25)-int(rotated_bow.get_width()/2),
             int(player.y+25)-int(rotated_bow.get_height()/2)))
# scale surface to screen (2x)
screen.blit(pygame.transform.scale(display,(screen_width,screen_height)),(0,0))
pygame.display.update()
clock.tick(60)
martineau
  • 119,623
  • 25
  • 170
  • 301
Mike67
  • 11,175
  • 2
  • 7
  • 15