2013-07-17 74 views
1

我在更新鼠标位置和检查由于等级滚动导致的实体碰撞(鼠标和实体之间)时遇到问题。我已经使用了摄像头功能,从这个问题:How to add scrolling to platformer in pygame在pygame中使用鼠标获取世界坐标

我曾尝试使用相机功能上的鼠标是这样的:

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 

但mouse.rect始终设置为608, 0。有人可以帮我弄这个吗?鼠标类看起来是这样的:

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 

每次我点击屏幕,并使之通过碰撞试验,它总是使用屏幕上的点,但是我需要在地图上的点(如果是有道理的)。例如,屏幕尺寸为640x640。如果我点击左上角,鼠标位置将始终为0,0但是,实际地图坐标可能在屏幕的顶部角落320,180。我试图使用相机和鼠标更新所有内容,唯一真正的结果是当我将camera.update功能应用于鼠标时,但这会阻止播放器成为滚动的原因,因此我试图用mouse.rect更新mouse.rect这个功能。

尝试代码:

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 With Offset: ", pos 
     print "Mouse Offset: ", mouse_offset 
     replace_block(pos) 

回答

1

相机计算屏幕由给定的世界坐标的坐标。

由于鼠标的位置已经是屏幕坐标,如果你想获得鼠标下的瓷砖,你必须。减去偏移,不加它。

您可以在下面的方法添加到Camera类:

def reverse(self, pos): 
    """Gets the world coordinates by screen coordinates""" 
    return (pos[0] - self.state.left, pos[1] - self.state.top) 

,并使用它像这样:

mouse_pos = camera.reverse(pygame.mouse.get_pos()) 
    if hit_block: 
     replace_block(mouse_pos) 
2

当你读到鼠标这是屏幕坐标。由于您正在滚动,因此您需要世界坐标来检查碰撞。

你渲染循环简化为

# draw: x+offset 
for e in self.entities: 
    screen.draw(e.sprite, e.rect.move(offset)) 

这是一样的draw(world_to_screen(e.rect))

你的点击会collidepoint(screen_to_world(pos))

# mouseclick 
pos = event.pos[0] + offset.left, event.pos[1] + offset.top 
for e in self.entities: 
    if e.collidepoint(pos): 
     print("click:", pos) 
+0

我说我的代码到实际的答案,似乎有一个问题,即当屏幕高度或宽度超过屏幕高度或宽度时,偏移量开始减小 – ReallyGoodPie

+1

如果将完整代码粘贴到pastebin(所以我可以运行它)我可以看一看。 – ninMonkey

+0

http://pastebin.com/Sx1KKBU2这是我的完整代码。 – ReallyGoodPie