如何在 Pygame 中将鼠标位置调整到相机坐标

How to adjust mouse position to camera coordinates in Pygame

我正在制作一个自上而下的游戏,到目前为止我已经添加了相机滚动。

此游戏的其中一项机制是可以将球扔向您的鼠标。

但是,由于我添加了相机滚动,我在尝试计算鼠标相对于相机滚动的位置时遇到了问题。

这是我计算滚动值的方法:

    self.true_scroll[0] += (self.player.loc[0] - self.true_scroll[0] - self.screen_size[0] / 2 + self.player.width / 2) / 15
    self.true_scroll[1] += (self.player.loc[1] - self.true_scroll[1] - self.screen_size[1] / 2 + self.player.height / 2) / 15
    
    self.scroll = self.true_scroll.copy()
    self.scroll[0] = int(self.scroll[0])
    self.scroll[1] = int(self.scroll[1])

这是我尝试根据滚动获取鼠标位置并将其扔向该位置的代码:

    mx, my = pygame.mouse.get_pos()
    
    mx -= scroll[0]
    my -= scroll[1]

    #For the scroll, I'm using the true_scroll value

    dx, dy = mx - self.loc[0], my - self.loc[1]
    angle = math.atan2(dy, dx)
    
    print(dx, dy)
            
    self.balls.append(Ball([self.loc[0], self.loc[1]], [math.cos(angle), math.sin(angle)]))

结果是球没有跟随鼠标的位置,而是去了远离鼠标的奇怪方向的位置。

如何使鼠标位置相对于滚动值?

我自己想出来了!其实还挺简单的。

我所要做的不是减去鼠标位置,而是玩家的位置减去滚动值。

于是代码变成了这样:

    mx, my = pygame.mouse.get_pos()

    sx, sy = self.loc[0] - scroll[0], self.loc[1] - scroll[1]
    
    dx, dy = mx - sx, my - sy
    angle = math.atan2(dy, dx)
                        
    self.balls.append(Ball([self.loc[0], self.loc[1]], [math.cos(angle), math.sin(angle)]))

希望这个回答对其他人有帮助