繁体   English   中英

有没有办法在 pygame 中舍入鼠标 position?

[英]Is there a way to round the mouse position in pygame?

我尝试在我的游戏中制作一个简单的系统,玩家在鼠标 position 所在的位置射击。 但是当我得到鼠标 position 时,我得到一个浮点元组(我想这就是它的名字)

有什么办法可以圆鼠标position。

这是代码(我已经对其进行了更改,因此打印了鼠标位置而不是我的整个游戏,但是您会得到它的乐趣)

import pygame as pg

class Game:

    def __init__(self):

        pg.init()
        pg.display.init()

        self.screen = pg.display.set_mode((500, 500))
        self.clock = pg.time.Clock()


    def update(self):

        print(pg.mouse.get_pos())


    def run(self):

        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.update()


    def quit(self):

        pg.quit()

g = Game()
while True
g.update()

这就是错误

self.pos += self.vel * self.game.dt ## This is a line of code that makes the movement smooth ## TypeError: can't multiply sequence by non-int of type 'float'

但正如您所见, print(pg.mouse.get_pos())的 output 不是浮点数。 有什么想法吗?

鼠标position是整数值,但self.game.dt不是整数。

如果self.vel是一个列表或元组, self.vel * self.game.dt不会做你所期望的。 它不会将列表的每个元素相乘,而是将列表翻倍。

您必须单独更改坐标的分量:

self.pos += self.vel * self.game.dt

self.pos = (
    self.pos[0] + self.vel[0]*self.game.dt, 
    self.pos[1] + self.vel[1]*self.game.dt)

如果self.pos不是一个元组而是一个列表,它可以更短:

self.pos[0] += self.vel[0]*self.game.dt 
self.pos[1] += self.vel[1]*self.game.dt

Pygame 提供pygame.math.Vector2用于向量算术。

暂无
暂无

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

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