Isometric Tilemap is Not Lining Up Properly

40 Views Asked by At

I am creating an isometric minecraft clone and my code is working fine. I use a rounding function to round the players position so that the blocks snap to a grid. The image for the block is 32x32 pixels exactly and everything in the image is symmetrical.

I currently have the rounding function set to 16 pixels on the X axis and 8 pixels on the Y axis. The problem lies within the Y axis as this causes some blocks to overlap if you do not place them in the right order. I do not know how to fix this, as I have already tried playing around with the rounding function. Help would be appreciated. Here is the code:

import pygame

pygame.init()
win = pygame.display.set_mode((480,320))
pygame.display.set_caption(("Mini Minecraft"))
block = pygame.image.load("Stone.png")
pygame.display.set_icon(block)
background = pygame.image.load("Background.png")
running = True

positions = []

def roundToMultiple(n, m):
    return round(n / m) * m

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            
        if event.type == pygame.MOUSEBUTTONDOWN:
            placeX, placeY = event.pos  
            placeXRound = roundToMultiple(placeX, 16)
            placeYRound = roundToMultiple(placeY, 8)
            positions.append((placeXRound, placeYRound))

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                positions = []

    mouseX, mouseY = pygame.mouse.get_pos()
    
    mouseXRound = roundToMultiple(mouseX, 16)
    mouseYRound = roundToMultiple(mouseY, 8)

    if mouseXRound > 448:
        mouseXRound = 448
    if mouseYRound > 288:
        mouseYRound = 288

    win.blit(background, (0,0))
    for pos in positions:
        win.blit(block, pos)
    win.blit(block, (mouseXRound, mouseYRound))
    pygame.display.update()

1

There are 1 best solutions below

0
Rabbid76 On

You only need to sort the list of points. Sort the list according to the x-coordinate and the inverse y-coordinate (positions.sort(key=lambda p: (p[0], -p[1]))):

if event.type == pygame.MOUSEBUTTONDOWN:
    placeX, placeY = event.pos  
    placeXRound = roundToMultiple(placeX, 16)
    placeYRound = roundToMultiple(placeY, 8)
    positions.append((placeXRound, placeYRound))
    positions.sort(key=lambda p: (p[0], -p[1]))