2

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)
Qiu YU
  • 517
  • 4
  • 20
Levi
  • 51
  • 5

2 Answers2

3

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

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
1

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.

Cribber
  • 2,513
  • 2
  • 21
  • 60