Move the player in the position of the mouse in pygame

一笑奈何 提交于 2019-12-02 05:12:13

Making an object follow the mouse is pretty easy if you know how to use vectors. You just need to create a vector that points to the target (in this case the mouse) by subtracting the target position from the position of the object:

heading = pg.mouse.get_pos() - self.pos  # self.pos is a pygame.math.Vector2

Then move the object by adding this vector to its position vector:

self.pos += heading * 0.1
self.rect.center = self.pos  # Update the rect of the sprite as well.

I also scale the heading vector here, otherwise it would move to the target immediately. By multiplying it by 0.1 the speed will be a tenth of the distance to the target (the length of the heading vector).

Here's a minimal, complete example:

import pygame as pg
from pygame.math import Vector2


class Entity(pg.sprite.Sprite):

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

    def update(self):
        # Get a vector that points from the position to the target.
        heading = pg.mouse.get_pos() - self.pos
        self.pos += heading * 0.1  # Scale the vector to the desired length.
        self.rect.center = self.pos


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

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

        all_sprites.update()

        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

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


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

Here's a version without vectors and sprites if you're not familiar with them. It does pretty much the same as the code above.

import pygame as pg
from pygame.math import Vector2


def main():
    pg.init()
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    image = pg.Surface((30, 30))
    image.fill(pg.Color('dodgerblue1'))
    x, y = 300, 200  # Actual position.
    rect = image.get_rect(center=(x, y))  # Blit position.

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

        mouse_pos = pg.mouse.get_pos()
        # x and y distances to the target.
        run = (mouse_pos[0] - x) * 0.1  # Scale it to the desired length.
        rise = (mouse_pos[1] - y) * 0.1
        # Update the position.
        x += run
        y += rise
        rect.center = x, y

        screen.fill((30, 30, 30))
        screen.blit(image, rect)

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


if __name__ == '__main__':
    main()
    pg.quit()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!