如何使粒子跟随我在pygame中的鼠标 [英] how to make particles follow my mouse in pygame

查看:78
本文介绍了如何使粒子跟随我在pygame中的鼠标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确保单击鼠标时出现的颗粒跟随鼠标移动.由于某种原因,这些粒子正好跟随我到左上方.谁能告诉我我在做什么错?

I'm trying to make sure that the particles that arise when I click my mouse follow my mouse. For some reason, the particles just follow me to the top left. Can anyone tell me what I am doing wrong?

这是我的代码:

import pygame
import sys
import random
import math

from pygame.locals import *
pygame.init()

clock = pygame.time.Clock()
screen = pygame.display.set_mode((500,500))
particles = []
while True:
    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == MOUSEBUTTONDOWN:
            mx,my = pygame.mouse.get_pos()
            particles.append([[pygame.Rect(mx,my,10,10)]])
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        
    for particle in particles:
        mx,my = pygame.mouse.get_pos()
        pygame.draw.rect(screen,(255,255,255),particle[0][0])
        radians = math.atan2((particle[0][0].y - my),(particle[0][0].x -mx))
        dy1 = math.sin(radians)
        dx1 = math.cos(radians)
        particle[0][0].x -= dx1
        particle[0][0].y -= dy1
    
    pygame.display.update()
    clock.tick(60)

推荐答案

之所以引起该问题,是因为 round 所得到的坐标来解决问题:

The issue is caused, because pygame.Rect stores integral values. If you add an floating point value, then the fraction part gets lost and the result is truncated. round the resulting coordinates to solve the issue:

particle[0][0].x = round(particle[0][0].x - dx1)
particle[0][0].y = round(particle[0][0].y - dy1)


注意,将 pygame.Rect 对象附加到列表中,而不是将 pygame.Rect 列表的列表附加到列表中即可:


Note, it is sufficient to append a pygame.Rect object to the list, rather than a list of a list of pygame.Rect:

particles.append([[[pygame.Rect(mx,my,10,10)]])

particles.append(pygame.Rect(mx,my,10,10))


示例:


Example:

particles = []
while True:
    screen.fill((0,0,0))

    mx, my = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == MOUSEBUTTONDOWN:
            particles.append(pygame.Rect(mx, my, 10, 10))
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        
    for particle in particles:
        pygame.draw.rect(screen, (255,255,255), particle)
        radians = math.atan2(my - particle.y, mx - particle.x)
        particle.x = round(particle.x + math.cos(radians))
        particle.y = round(particle.y + math.sin(radians))


有关更复杂的方法,请参见如何在pygame中流畅移动

这篇关于如何使粒子跟随我在pygame中的鼠标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆