过去几个小时一直在做这个,试图制作一个小程序,其中图像追逐光标。到目前为止,我已经设法使图像直接位于光标上方并沿着该方向移动。然而,我需要的是图像真正“追逐”光标,因此它需要最初远离光标,然后在它后面运行,直到它位于鼠标之上。
基本上,我遇到了问题和需要修复的问题,这是我到目前为止所得到的:
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
and me_y
将是浮点数,而不是整数。这是好事;当您每步向东北移动 2 个像素时,即向北移动 1.414 像素,向东移动 1.414 像素。如果您将其每一步舍入为 1 像素,那么沿对角线方向移动时,您的移动速度将比垂直方向上慢 41%,这看起来有点愚蠢。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)