Pygame让对象追逐鼠标光标

3 投票
1 回答
2926 浏览
提问于 2025-04-30 18:07

我花了几个小时在这个问题上,想做一个小程序,让一张图片跟着鼠标移动。到目前为止,我已经让图片直接在鼠标上面,并且跟着鼠标移动。不过我想要的是让图片真正地“追逐”鼠标,也就是说,图片一开始要离鼠标远一点,然后再跑过去,最后停在鼠标上面。

我现在遇到了一些问题,不知道哪里出错了,也不知道该怎么修正。以下是我目前的代码:

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个小时了。任何帮助都非常感谢!谢谢 :)

暂无标签

1 个回答

2

假设你想让猫以固定的速度移动,比如每次移动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_xme_y是浮点数,而不是整数。这是好事;因为当你每次向东北方向移动2个像素时,实际上是向北和向东各移动1.414个像素。如果你把这个四舍五入到每次1个像素,那么在对角线方向移动时,你的速度会比垂直方向慢41%,这看起来就会很奇怪。

撰写回答