[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] layers and/or tiles?
On Feb 1, 2008, at 12:51 PM, Gregg Jensen wrote:
Sounds like just the kind of thing I was looking for. Many thanks.
Gregg
Going over that code again I wanted to point out a cute little hack
that greatly simplifies things (both conceptually and in the code).
(In the Panel base class):
def localize_event(self, event):
"""Return a new event with coordinates local to the panel"""
event_info = dict(event.dict) # copy event data into a new dict
if 'pos' in event_info:
gx, gy = event_info['pos']
event_info['pos'] = (gx - self.rect.left, gy - self.rect.top)
return pygame.event.Event(event.type, event_info)
This takes any pygame event as its input and returns an equivalent
event object with its position local to the panel rather than the
pygame display. This way the controls can all be positioned relative
to the panel and don't have to care where the panel actually is.
This means the panels can even handle mouse events properly when they
are sliding.
Another notable piece happens in this method, which is called each
frame when the panel is sliding:
def slide(self):
old_pos = self.slide_pos
self.slide_pos += self.slide_vel
self.rect.left, self.rect.top = vector.to_tuple(self.slide_pos)
# Create a simulated mouse move event and send it to the event handler
# Even though we are moving, not the mouse, the effect is the same
mm_event = pygame.event.Event(pygame.MOUSEMOTION,
pos=pygame.mouse.get_pos(), buttons=pygame.mouse.get_pressed(),
rel=vector.to_tuple(-self.slide_vel))
self.mouse_move(mm_event)
The interesting part is at the end where it manufactures a mouse move
event and sends it to itself. This makes it properly handle things
like mouse over effects and what not. Otherwise things may not look
right if the mouse was positioned over a control before the slide
started or after it ends.
-Casey