Search code examples
pythonmathpygamealignmentisometric

Pygame Isometric Grid?


Is there an algorithm for snapping to an isometric grid?

This is the one I came up with:

def Iso(argument0,argument1):
    a = round(pygame.mouse.get_pos()[1]/argument1 - pygame.mouse.get_pos()[0]/argument0);
    b = round(pygame.mouse.get_pos()[1]/argument1 + pygame.mouse.get_pos()[0]/argument0);
    x = (b - a)/2*argument0;
    y = (b + a)/2*argument1;
    return (x,y)

and it looks like this: Alignment doesn't work!

Anyone got any ideas??

Here is my code:

import pygame
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,480))
curs=pygame.image.load('white-0.gif').convert()
curs.set_alpha(100)
g1=pygame.image.load('green-0.gif').convert()
tiles=[]

def Iso(argument0,argument1):
    a = round(pygame.mouse.get_pos()[1]/argument1 - pygame.mouse.get_pos()[0]/argument0);
    b = round(pygame.mouse.get_pos()[1]/argument1 + pygame.mouse.get_pos()[0]/argument0);
    x = (b - a)/2*argument0;
    y = (b + a)/2*argument1;
    return (x,y)

class Tile(object):
    def __init__(self,spr,pos1,pos2):
        self.pos=(pos1,pos2)
        self.spr=spr
while True:
    screen.fill((90,90,0))
    mse=pygame.mouse.get_pos()
    for e in pygame.event.get():
        if e.type==QUIT:
            exit()
        if e.type==MOUSEBUTTONUP:
            if e.button==1:
                pos=Iso(16,16)
                tiles.append(Tile(g1,pos[0],pos[1]))
    pos=Iso(16,16)
    screen.blit(curs, (pos[0],pos[1]))
    for t in tiles:
        screen.blit(t.spr,t.pos)
    pygame.display.update()

UPDATE: Managed to get it to work like this: Working Isometrics!! Just having a few depth issues..


Solution

  • You are converting pixels to an isometric view. Presumably, you want to snap to (isometric) tiles instead.

    Multiply your isometric x,y by (width/2),(height/2) where width and height are your isometric tile dimensions. Since that radically changes the scale, you might want to divide both by a constant; if you don't do that, only moving the mouse in the very top left of your screen will make something show up.

    Apart from the isometric part, this is exactly what one would do for a top-down grid.