1

When i hit play my cursor seems to be on the top left corner of the rect, i am very fresh to using thonny/pygames and can't figure out how to get my mouse cursor to be in the center of the rect.

Any help would be greatly appreciated, thanks! :)

import pygame  # accesses pygame files
import sys  # to communicate with windows

# game setup ################ only runs once
pygame.init()  # starts the game engine
clock = pygame.time.Clock()  # creates clock to limit frames per second
FPS = 60  # sets max speed of main loop
SCREENSIZE = SCREENWIDTH, SCREENHEIGHT = 1000, 800  # sets size of screen/window
screen = pygame.display.set_mode(SCREENSIZE)  # creates window and game screen

# set variables for colors RGB (0-255)
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
yellow = (255, 255, 0)
green = (0, 255, 0)

gameState = "running"  # controls which state the games is in
# game loop #################### runs 60 times a second!
while gameState != "exit":  # game loop - note:  everything in the mainloop is indented one tab

    for event in pygame.event.get():  # get user interaction events
        print (event)
        if event.type == pygame.QUIT:  # tests if window's X (close) has been clicked
            gameState = "exit"  # causes exit of game loop


    # your code starts here ##############################

        screen.fill(black)

        mouse_position = pygame.mouse.get_pos()
        player1X = mouse_position[0]
        player1Y = mouse_position[1]


        player1 = pygame.draw.rect(screen, red, (player1X, player1Y, 50, 50))

        pygame.display.flip()  # transfers build screen to human visable screen
        clock.tick(FPS)  # limits game to frame per second, FPS value





    # your code ends here ###############################
    pygame.display.flip()  # transfers build screen to human visable screen
    clock.tick(FPS)  # limits game to frame per second, FPS value

# out of game loop ###############
print("The game has closed")  # notifies user the game has ended
pygame.quit()   # stops the game engine
sys.exit()  # close operating system window
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
FreshApple
  • 49
  • 3

1 Answers1

0

Create a pygame.Rect object with the size of the player and set the center position of the rectangle by the mouse cursor position:

player1 = pygame.Rect(0, 0, 50, 50)
player1.center = mouse_position
pygame.draw.rect(screen, red, player1)

Note, a pygame.Rect has a bunch of virtual attributes, which can be used to get an set its size and position.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174