How can I make a sprite snap to an isometric grid? [duplicate]

  Kiến thức lập trình

I am currently in the works of creating an 8-bit style minecraft clone that uses isometric projection as opposed to true 3D. At the moment I am using a square grid snapping system that rounds the players position when you place a block to 16 pixels on the X axis and 8 on the Y axis.

This works ok, but can cause some blocks to overlap and not match the relative isometric position of other blocks if not placed properly.

My question is: how can I make this square snapping system isometric? I watched a few YouTube videos on the subject, (but could not find any specific answers) and now know that an isometric grid is a square grid rotated 45 degrees and halved vertically. I tried using ChatGPT to get some ideas and some code, but it was just too buggy for me to fix.

The “grass.png” image I am using is an 8×8 isometric cube sprite upscaled to 32×32 pixels (using a photo editor) and is perfectly symmetrical.

I do not want a flat isometric tilemap that can only have one layer of blocks placed on it, nor do I want to sort the inverse Y positions of each block so that they don’t overlap, I want a snapping function that allows multiple layers, so I can place blocks on top of one another from each of the screen borders and allows all blocks to line up relative to the isometric grid. (which will also stop overlapping)

I am new to Pygame and don’t understand much of the complicated code in some of these other “duplicates” of my question. I would really like an explaination of how I can implement this and what code would be neccessary!

Here’s what the game looks like

import pygame

window = pygame.display.set_mode((480,320))
running = True

player = pygame.image.load("grass.png")
positions = []

def round_to_multiple(x, multiple):
    return round(x / multiple) * multiple

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

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            player_x, player_y = event.pos
            positions.append([round_to_multiple(player_x, 16), round_to_multiple(player_y, 8)])

    window.fill("white")
    for pos in positions:
        window.blit(player, pos)
    window.blit(player, (pygame.mouse.get_pos()))
    pygame.display.update()
pygame.quit()

3

LEAVE A COMMENT