簡體   English   中英

如何在 pygame 中讓粒子跟隨我的鼠標

[英]how to make particles follow my mouse in pygame

我試圖確保單擊鼠標時出現的粒子跟隨鼠標。 出於某種原因,粒子只是跟着我到左上角。 誰能告訴我我做錯了什么?

這是我的代碼:

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)

問題是由於pygame.Rect存儲整數值引起的。 如果添加浮點值,則小數部分會丟失並且結果會被截斷。將結果坐標round以解決問題:

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

注意,append 一個pygame.Rect object 的列表就足夠了,而不是一個列表的列表pygame.Rect

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

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

例子:

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 中進行平滑移動

它通過簡單的調整即可工作:

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

問題是您嘗試一次將粒子移動不到一個像素,這導致它們根本不移動並且運動丟失。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM