【问题标题】:Pygame: Image chasing the mouse cursor from certain length [duplicate]Pygame:图像从一定长度追逐鼠标光标[重复]
【发布时间】:2019-08-05 17:22:37
【问题描述】:

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

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

【问题讨论】:

    标签: python pygame mouseevent mouse-cursor


    【解决方案1】:

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

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

    最小示例: repl.it/@Rabbid76/PyGame-FollowMouse

    另见Move towards target

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 2014-04-08
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多