繁体   English   中英

如何在 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)]))

希望这个答案可以帮助其他人

暂无
暂无

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

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