Pygame: 图像从一定长度追逐鼠标光标

Pygame: Image chasing the mouse cursor from certain length

最初图像开始向 (0,0) 方向移动。在每一帧中,对象使用 pygame.mouse.get_pos() 查看光标的当前位置,并将其方向更新为 direction = .9*direction + v,其中 v 是一个长度为 10 的向量,它指向你的中心图片到鼠标位置。

这是我的:

    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)

问题是当我运行代码时,图像随着鼠标光标移动,而不是跟随它移动。我该如何改进?

如果你想让图片稍微朝鼠标的方向移动,那么你必须在图片的当前位置添加一个向量,它指向鼠标的方向。的长度必须小于到鼠标的距离:

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

这会导致球在每一帧中向鼠标移动一小步。

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()

最小示例: repl.it/@Rabbid76/PyGame-FollowMouse

另见 Move towards target