How can i give my image an initial position before it starts moving with the mouse?

Viewed 80

I'm working on this pygame game and i'm just getting started but got a bit confused because i want the image to move in the x-axis along with the mouse but when i run the program i want the image to show up at the center or the 'floor' but appears at the left side instead. This is my code and a screenshot of what's happening.

import pygame
import sys

pygame.init()
pygame.mixer.init()

WIDTH, HEIGHT = 400, 500
FPS = 60
TITLE = 'FOOD DROP'
SIZE = 190

# Colors

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE_SKY = (152, 166, 255)

# Display

SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)

# Surfaces

floor_surface = pygame.Surface((WIDTH, 100))
floor_surface.fill(BLUE_SKY)
floor_rect = floor_surface.get_rect(midbottom=(200, 500))

# Images

LOAD_DITTO = pygame.image.load('Graphics/ditto.png')
DITTO = pygame.transform.scale(LOAD_DITTO, (SIZE, SIZE))

# Time

CLOCK = pygame.time.Clock()


class Figure:

    def draw_figure(self, mouse_x):
        SCREEN.blit(DITTO, (mouse_x - 90, 330))


# Game loop

SCREEN_UPDATE = pygame.USEREVENT
# main_game = Main()
figure = Figure()

running = True
while running:
    CLOCK.tick(FPS)
    mx, my = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    SCREEN.fill(WHITE)
    SCREEN.blit(floor_surface, floor_rect)
    figure.draw_figure(mx)
    pygame.display.update() 

When i run the program, this happens:

enter image description here

And i want the image to appear right at the center or the x-axis, not the border, i don't know why is this happening. Just to state, that screenshot was taken when the mouse hadn't been placed over the display.

1 Answers

If the mouse pointer is not in the window (out of focus), the initial position of the mouse pointer is (0, 0). Therefore pygame.mouse.get_pos returns (0, 0). It is also not possible to set the mouse position with pygame.mouse.set_pos if it is not in the window.
Initialize the variables mx and mx with the center of the window. Change the mouse position only when the mouse pointer is in the window (in focus). pygame.mouse.get_focused can be used to test whether the mouse is in the window.

mx, my = SCREEN.get_rect().center

running = True
while running:
    CLOCK.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if pygame.mouse.get_focused():
        mx, my = pygame.mouse.get_pos()

    SCREEN.fill(WHITE)
    SCREEN.blit(floor_surface, floor_rect)
    figure.draw_figure(mx)
    pygame.display.update() 

pygame.quit()
sys.exit()
Related