Pygame Slider one pixel too short

Viewed 53

so I'm trying to make a slider in, pygame, but ran into a rather annoying problem. for some reason my slider is 1 pixel too short of the specified value on the right side.

import pygame

pygame.init()

screen_height = 700
screen_width = 1500

resolution = [screen_width, screen_height]

screen = pygame.display.set_mode(resolution)

rectangle_coordinates = [100, 100]
rectangle_size = [100, 100]
rectangle = pygame.Rect(rectangle_coordinates[0], rectangle_coordinates[1], 100, 100)

click_zone_coordinates = [rectangle_size[0]/2, rectangle_size[1]]
click_zone_size = [screen_width-rectangle_size[0], rectangle_size[1]]
click_zone = pygame.Rect(click_zone_coordinates[0], click_zone_coordinates[1], click_zone_size[0], click_zone_size[1])

# colors
white = [255, 255, 255]
black = [0, 0, 0]
purple = [128, 0, 128]

running = True

while running:
    screen.fill(white)
    rectangle = pygame.Rect(rectangle_coordinates[0], rectangle_coordinates[1], rectangle_size[0],  rectangle_size[1])
    def is_over(rect, pos):
        return True if rect.collidepoint(pos) else False

    pos = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
        if pygame.mouse.get_pressed(3)[0]:
            if is_over(click_zone, pos):
                rectangle_coordinates[0] = pos[0]-rectangle_size[0]/2

    pygame.draw.rect(screen, purple, click_zone)
    pygame.draw.rect(screen, black, rectangle)

    pygame.display.update()
pygame.quit()

also, I'm trying to base the values off the screen dimensions, so it is scale-able.

it would be terrific if someone knew a fix for this.

1 Answers

See pygame.Rect.collidepoint:

Returns true if the given point is inside the rectangle. A point along the right or bottom edge is not considered to be inside the rectangle.

Therefore you need to increase the width of the click_zone by 1:

click_zone = pygame.Rect(
    click_zone_coordinates[0], click_zone_coordinates[1], 
    click_zone_size[0] + 1, click_zone_size[1])

To make the slider depend on the size of the screen, you need to calculate the rectangle click_zone in the application loop depending on the width of the screen:

while running:
    click_zone = pygame.Rect(
        rectangle_size[0]//2, rectangle_size[1], 
        screen.get_width() - rectangle_size[0] + 1, rectangle_size[1])

    # [...]
Related