python - 如何在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)
请注意,将对象附加到列表中就足够了pygame.Rect
,而不是列表的列表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 中进行平滑移动
推荐阅读
- wordpress - Wordpress:即使在重新安装肯定有效的版本备份后仍重定向到 wp-admin/install.php
- javascript - 使用 removeChild() [Vanilla Javascript] 从父 DOM 中删除特定索引子项
- php - 变量和引号 - 传递给函数时的区别
- javascript - 如何防止组件随着不断增长的视图向上移动
- c# - 使用 PutObjectRequest 写入 S3,同时仍生成流
- javascript - 使用 Web Audio Api AudioWorklet 从音频流中抓取比特并进行 BPM 检测
- xamarin - Xamarin Forms:转换器的多个项目
- javascript - 仅在来自特定页面时创建该链接
- sql - 使用两个标准查找查询中的差异
- c# - ASP NET Web API google 身份验证问题 HTTP 404