Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

python - 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. But when i get the mouse position, i get a float tuple (I think that's what it's called)

Is there any way to round the mouse 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. Any ideas what's going on?

question from:https://stackoverflow.com/questions/65896485/is-there-a-way-to-round-the-mouse-position-in-pygame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The mouse position is an integral value, but self.game.dt is not integral.

If self.vel is a list or tuple, self.vel * self.game.dt doesn't do what you'd expect. 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[0] += self.vel[0]*self.game.dt 
self.pos[1] += self.vel[1]*self.game.dt

Pygame provides pygame.math.Vector2 for vector arithmetic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...