Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pygame shapes cannot take non integer arguments

Does it matter that in the Pygame module, the shapes cannot take float values as their arguments?

This is raised due to the fact that I am currently making a relatively basic physics simulation, and using pygame to do the graphics, and in a physics simulation, it rarely/never happens that an object is centred such that it has an integer value.

I am wondering mainly if this would have a significant effect on the accuracy of the simulation?

like image 544
Bob Avatar asked Sep 03 '26 01:09

Bob


1 Answers

I usually recommend storing the position and velocity of the game objects as vectors (which contain floats) to keep the physics accurate. Then you can first add the velocity to the position vector and afterwards update the rect of the object which serves as the blit position and can be used for collision detection. You don't have to convert the position vector to ints before you assign it to the rect, since pygame will do that automatically for you.

Here's a little example with an object that follows the mouse.

import pygame as pg
from pygame.math import Vector2


class Player(pg.sprite.Sprite):

    def __init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((30, 30))
        self.image.fill(pg.Color('steelblue2'))
        self.rect = self.image.get_rect(center=pos)
        self.direction = Vector2(1, 0)
        self.pos = Vector2(pos)

    def update(self):
        radius, angle = (pg.mouse.get_pos() - self.pos).as_polar()
        self.velocity = self.direction.rotate(angle) * 3
        # Add the velocity to the pos vector and then update the 
        # rect to move the sprite.
        self.pos += self.velocity
        self.rect.center = self.pos


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    color = pg.Color('steelblue2')
    all_sprites = pg.sprite.Group()
    player = Player((100, 300), all_sprites)

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)
        txt = font.render(str(player.pos), True, color)
        screen.blit(txt, (30, 30))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()
like image 53
skrx Avatar answered Sep 05 '26 15:09

skrx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!