Search code examples
pythonpygamemouseeventmouse-cursor

Pygame: Image chasing the mouse cursor from certain length


Initially the image starts moving in the direction (0,0). During each frame, the object looks at the current location of the cursor using pygame.mouse.get_pos() and updates it's direction to be direction = .9*direction + v where v is a vector of length 10 that points from the center of your image to the mouse position.

this is what i have:

    from __future__ import division
import pygame
import sys
import math
from pygame.locals import *


class Cat(object):
    def __init__(self):
        self.image = pygame.image.load('ball.png')
        self.x = 1
        self.y = 1

    def draw(self, surface):
        mosx = 0
        mosy = 0
        x,y = pygame.mouse.get_pos()
        mosx = (x - self.x)
        mosy = (y - self.y)
        self.x = 0.9*self.x + mosx
        self.y = 0.9*self.y + mosy
        surface.blit(self.image, (self.x, self.y))
        pygame.display.update()


pygame.init()
screen = pygame.display.set_mode((800,600))
cat = Cat()
Clock = pygame.time.Clock()

running = True
while running:
    screen.fill((255,255,255))
    cat.draw(screen)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    Clock.tick(40)

The issue its that when i'm running the code, the image moves with the mouse cursor, instead of going after it. How can i improve that?


Solution

  • If you want, that the image slightly moves in the direction of the mouse, then you have to add a vector to the current position of the image, which points in the direction of the mouse. The length of the has to be less than the distance to the mouse:

    dx, dy = (x - self.x), (y - self.y)
    self.x, self.y = self.x + dx * 0.1, self.y + dy * 0.1 
    

    this causes that the ball makes a small step to the mouse in each frame.

    class Cat(object):
        def __init__(self):
            self.image = pygame.image.load('ball.png')
            self.x = 1
            self.y = 1
            self.t = 0.1
    
        def draw(self, surface):
            mosx = 0
            mosy = 0
            x,y = pygame.mouse.get_pos()
            dx, dy = (x - self.x), (y - self.y)
            self.x, self.y = self.x + dx * self.t, self.y + dy * self.t
            w, h = self.image.get_size()
            surface.blit(self.image, (self.x - w/2, self.y - h/2))
            pygame.display.update()
    

    Minimal example: repl.it/@Rabbid76/PyGame-FollowMouse

    2

    See also Move towards target