2013-07-17 77 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