python - Getting World Coordinates with mouse in pygame -
i having trouble updating mouse position , checking entity collisions (between mouse , entity) due level scrolling. have used camera function question: how add scrolling platformer in pygame
i have tried use camera function on mouse this:
def update(self, target, target_type, mouse): if target_type != "mouse": self.state = self.camera_func(self.state, target.rect) else: new_pos = self.camera_func(mouse.rect, target.rect) mouse.update((new_pos[0], new_pos[1])) print mouse.rect
but mouse.rect consistently set 608, 0
. can me this? mouse class looks this:
class mouse(entity): def __init__(self, pos): entity.__init__(self) self.x = pos[0] self.y = pos[1] self.rect = rect(pos[0], pos[1], 32, 32) def update(self, pos, check=false): self.x = pos[0] self.y = pos[1] self.rect.top = pos[1] self.rect.left = pos[0] if check: print "mouse pos: %s" %(self.rect) print self.x, self.y
everytime click screen, , pass through collision test, uses point on screen, need point on map (if makes sense). example, screen size 640x640
. if click in top left corner, mouse position 0,0
however, actual map coordinates may 320,180
in top corner of screen. have attempted update camera , mouse, , real results when apply camera.update
function mouse, stop player being cause of scrolling, therefore attempted update mouse.rect
function.
attempted code:
mouse_pos = pygame.mouse.get_pos() mouse_offset = camera.apply(mouse) pos = mouse_pos[0] + mouse_offset.left, mouse_pos[1] + mouse_offset.top mouse.update(mouse_pos) if hit_block: print "mouse screen pos: ", mouse_pos print "mouse pos offset: ", pos print "mouse offset: ", mouse_offset replace_block(pos)
the camera calculates screen coordinate given world coordinate.
since mouse position screen coordinate, if want tile under mouse, have substract offset, not add it.
you can add following method camera
class:
def reverse(self, pos): """gets world coordinates screen coordinates""" return (pos[0] - self.state.left, pos[1] - self.state.top)
and use this:
mouse_pos = camera.reverse(pygame.mouse.get_pos()) if hit_block: replace_block(mouse_pos)
Comments
Post a Comment