[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] y-Sorted RenderGroup



Christopher Armstrong wrote:

>    steve> Hello,
>
>    steve>    I've developed a RenderUpdate group that sorts it's sprites on
>    steve> their y position, useful for things like Japaneese style RPGs where
>    steve> sprites closer to the bottom of the screen are drawn first, and
>    steve> sprites near the top of the screen are drawn last.
>
>Looking at the code, I see you sort based on rect.top instead of a logical y 
>position. In other words, it won't work if you want sprites in your game to 
>have various heights. I suppose the solution to this is to make all sprites
>contain a logical position independant of their location on the screen (ie,
>world location), and them map it onto the screen by that. (if you want to get
>fancy, you can have a 'hotspot' in each sprite that should line up with its
>logical location on-screen, but otherwise you can just use the bottom of the
>image [ie, where its feet/base meet the ground])
>
>
    Easy enough, pygame gives us a midbottom point for our Rects, so 
I'll just base my sort on that.  So my final y-sort looks like this:

def y_sort(a,b):
    return cmp(a.rect.midbottom, b.rect.midbottom)

    Wow, thanks for all your help, sometimes having hundreds of eyes 
looking at your code can solve a lot of problems.  Realizing that Python 
uses a quicksort, O(n log n) for its sorting algorithm, I wonder if 
could I do better with an insertion sort, which is O(n) for near sorted 
lists, which mine will be once my program is running (sprites won't be 
jumping around randomly, most of the time they'll be moving fairly slow).

    I wouldn't like to roll my own sprite routines, since I like 
pygame.sprite.Sprite too much.  If I did this for pure speed, I'd 
probably maintain a sorted list, and do an insertsort each time I call 
update() on my sprite list, not every paint.  I would probably keep 
track of what sprites are visible on screen, and only sort those.  I 
would like to try to work within pygame.sprite.Sprite, though.


____________________________________
pygame mailing list
pygame-users@seul.org
http://pygame.seul.org