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

时间:2019-03-14 17:40:48

标签: python pygame mouseevent mouse-cursor

最初,图像开始沿(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)

问题在于,当我运行代码时,图像将使用鼠标光标移动,而不是跟随它移动。我该如何改善呢?

1 个答案:

答案 0 :(得分:0)

如果要使图像沿鼠标方向稍微移动,则必须在图像的当前位置添加一个指向鼠标方向的矢量。的长度必须小于到鼠标的距离:

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