how to make particles follow my mouse in pygame

≡放荡痞女 提交于 2021-01-27 18:10:30

问题


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?

Here is my code:

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)

回答1:


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)

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

For an even more sophisticated approach see How to make smooth movement in pygame




回答2:


It works with a simple adjustment:

    dy1 = math.sin(radians) * 10
    dx1 = math.cos(radians) * 10

The problem is that you try to move the particles for less than a pixel at a time which results in them not moving at all and the movement being lost.



来源:https://stackoverflow.com/questions/63412401/how-to-make-particles-follow-my-mouse-in-pygame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!