繁体   English   中英

在pygame中使用鼠标获取世界坐标

[英]Getting World Coordinates with mouse 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的实际地图坐标可能为320,180 我试图使用相机和鼠标更新所有内容,唯一真正的结果是当我将camera.update函数应用于鼠标时,但这会阻止播放器成为滚动的原因,因此我尝试更新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)

当你读取鼠标的屏幕坐标时 由于您正在滚动,因此需要使用世界坐标来检查碰撞。

渲染循环简化为

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

这与draw( world_to_screen( e.rect ))相同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)

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

由于鼠标位置已经是屏幕坐标,如果要获取鼠标下的图块,则必须减去偏移量, 而不是添加它。

您可以将以下方法添加到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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM