我已经花了几个小时的时间制作一个小程序,让一张图片追逐鼠标指针。目前为止,我已经实现了使图片直接在鼠标指针上方并跟随其移动的功能。然而,我需要的是让图片实际上"追逐"鼠标指针,所以它需要最初离开鼠标指针并在追逐鼠标指针后最终到达鼠标指针上方。
基本上,在找出问题和需要修复的地方上遇到了障碍,以下是我目前的成果:
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)
也许代码并不是最好的状态,我已经折腾了五个小时以上。非常感谢任何帮助!谢谢 :)
self.x += 2
,甚至一次也不需要吗?为什么你要将mosx
和mosy
存储为实例属性,当它们只在draw
中本地使用?最重要的是,.9 * x + mosx
应该是做什么用的? - abarnert