Skip to main content
 首页 » 编程设计

python之Pygame使一个对象追逐光标

2025年05月04日10mayingbao

过去几个小时一直在做这个,试图制作一个小程序,让图像在其中追逐光标。到目前为止,我已经设法使图像直接位于光标上方并以这种方式跟随它。然而,我需要的是让图像真正“追逐”光标,因此它需要最初远离光标,然后追赶它,直到它到达鼠标上方。

基本上遇到了什么问题和要解决的问题,这是我到目前为止所得到的:

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) 

可能不是最好的编码状态,现在已经搞砸了 5 个多小时。任何帮助深表感谢!谢谢:)

请您参考如下方法:

假设您希望猫以固定速度移动,例如每刻 X 像素,您需要选择一个朝向鼠标光标的新位置 X 像素。 (如果你想让猫越靠近它移动得越慢,你可以选择一个位置,在当前位置和鼠标光标之间有一定百分比的距离。如果你想让它移动得越近,你需要除法而不是乘法。等等。但让我们首先坚持简单的。)

现在,如何将 X 像素移向鼠标光标?通常的描述方式是:找到从当前位置到光标方向的单位向量,然后将它乘以 X,然后得到相加的步骤。您可以将其简化为平方根:

# Vector from me to cursor 
dx = cursor_x - me_x 
dy = cursor_y - me_y 
 
# Unit vector in the same direction 
distance = math.sqrt(dx*dx + dy*dy) 
dx /= distance 
dy /= distance 
 
# speed-pixel vector in the same direction 
dx *= speed 
dy *= speed 
 
# And now we move: 
me_x += dx 
me_y += dy 

请注意,me_x 和 me_y 将是 float ,而不是整数。这是好事;当您每一步向东北移动 2 个像素时,即向北移动 1.414 像素,向东移动 1.414 像素。如果将其四舍五入为每步 1 个像素,那么沿对角线移动的速度将比垂直移动时慢 41%,这看起来有点傻。