Не могу понять, как поместить курсор мыши в центр прямоугольника
Когда я нажимаю кнопку воспроизведения, мой курсор оказывается в верхнем левом углу прямоугольника, я очень хорошо знаком с использованием thonny/pygames и не могу понять, как заставить курсор мыши находиться в центре прямоугольника.
Любая помощь будет принята с благодарностью, спасибо!:)
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
1 ответ
Создать pygame.Rect
объект размером с плейер и установите center
положение прямоугольника по положению курсора мыши:
player1 = pygame.Rect(0, 0, 50, 50)
player1.center = mouse_position
pygame.draw.rect(screen, red, player1)
Обратите внимание, что pygame.Rect
имеет набор виртуальных атрибутов, которые можно использовать для определения размера и положения набора.