Skip to content Skip to sidebar Skip to footer

Python & Pygame How To Move And Rotate Polygon Towards The Mouse Position?

(EDIT: The rotation doesn't matter too much to me anymore - just the movement. I am still curious and would love to know how to do the rotation however.) def angle_between(p1, p2):

Solution 1:

To move an object towards the mouse, you can use vectors. Just subtract the position from the mouse pos, normalize the resulting vector and mutliply it by the desired speed. That gives you the velocity vector which you can add to the self.pos each frame (also update the rect which serves as the blit position and for collision detection).

Call the Vector2.as_polar method (it returns the polar coordinates) to get the angle of the vector and then use it to rotate the original image.

import pygame as pg
from pygame.math import Vector2


classEntity(pg.sprite.Sprite):

    def__init__(self, pos, *groups):
        super().__init__(*groups)
        self.image = pg.Surface((50, 30), pg.SRCALPHA)  # A transparent image.# Draw a triangle onto the image.
        pg.draw.polygon(self.image, pg.Color('dodgerblue2'),
                        ((0, 0), (50, 15), (0, 30)))
        # A reference to the original image to preserve the quality.
        self.orig_image = self.image
        self.rect = self.image.get_rect(center=pos)
        self.vel = Vector2(0, 0)
        self.pos = Vector2(pos)

    defupdate(self):
        # Subtract the pos vector from the mouse pos to get the heading,# normalize this vector and multiply by the desired speed.
        self.vel = (pg.mouse.get_pos() - self.pos).normalize() * 5# Update the position vector and the rect.
        self.pos += self.vel
        self.rect.center = self.pos

        # Rotate the image.# `Vector2.as_polar` returns the polar coordinates (radius and angle).
        radius, angle = self.vel.as_polar()
        self.image = pg.transform.rotozoom(self.orig_image, -angle, 1)
        self.rect = self.image.get_rect(center=self.rect.center)


defmain():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    entity = Entity((100, 300), all_sprites)

    done = Falsewhilenot 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)

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


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

Post a Comment for "Python & Pygame How To Move And Rotate Polygon Towards The Mouse Position?"