简体   繁体   English

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

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

I have tried making a simple system in my game where the player shoots where the mouse position is.我尝试在我的游戏中制作一个简单的系统,玩家在鼠标 position 所在的位置射击。 But when i get the mouse position, i get a float tuple (I think that's what it's called)但是当我得到鼠标 position 时,我得到一个浮点元组(我想这就是它的名字)

Is there any way to round the mouse position.有什么办法可以圆鼠标position。

This is the code (I have it changed it so the mouse pos gets printed instead of my whole game, but you get the jyst of it)这是代码(我已经对其进行了更改,因此打印了鼠标位置而不是我的整个游戏,但是您会得到它的乐趣)

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()

And this is the error这就是错误

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'

But as you can see, the output of the print(pg.mouse.get_pos()) isn't a float.但正如您所见, print(pg.mouse.get_pos())的 output 不是浮点数。 Any ideas what's going on?有什么想法吗?

The mouse position is an integral value, but self.game.dt is not integral.鼠标position是整数值,但self.game.dt不是整数。

If self.vel is a list or tuple, self.vel * self.game.dt doesn't do what you'd expect.如果self.vel是一个列表或元组, self.vel * self.game.dt不会做你所期望的。 It doesn't multiply each element of the list, it doubles the list.它不会将列表的每个元素相乘,而是将列表翻倍。

You must change the components of the coordinate separately:您必须单独更改坐标的分量:

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)

If self.pos is not a tuple but a list, it can be made shorter:如果self.pos不是一个元组而是一个列表,它可以更短:

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

Pygame provides pygame.math.Vector2 for vector arithmetic. Pygame 提供pygame.math.Vector2用于向量算术。

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

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