在 python pygame 中,我试图让我的玩家从玩家中心开始向鼠标方向发射粒子
class Particle:
def __init__(self, ..., dx, dy, x, y):
self.dx = dx
self.dy = dy
self.x = x
self.y = y
self.Rect = self.img.get_rect()
def draw(self):
self.x += self.dx
self.y += self.dy
self.Rect.centerx = self.x
self.Rect.centery = self.y
screen.blit(self.img, (self.Rect.x, self.Rect.y))
theta 是玩家中心与鼠标之间的角度(以度为单位),范围从 0 到 360,
0 为 x 正方向
dx = math.cos(theta)
dy = math.sin(theta)
Particle(..., dx, dy, starting_x, starting_y)
然而粒子似乎朝随机方向发射?
完整代码:
import pygame
import math
FPS = 60
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
pygame.init()
screen = pygame.display.set_mode([300, 300])
clock = pygame.time.Clock()
class Particle:
def __init__(self, dx, dy, x, y):
self.dx = dx
self.dy = dy
self.x = x
self.y = y
self.Rect = pygame.Rect(100, 150, 5, 5)
def draw(self, screen):
self.x += self.dx
self.y += self.dy
self.Rect.centerx = self.x
self.Rect.centery = self.y
pygame.draw.rect(screen, BLUE, self.Rect)
particles = []
done = False
while not done:
screen.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if pygame.mouse.get_pressed()[0]:
mousex = pygame.mouse.get_pos()[0]
mousey = pygame.mouse.get_pos()[1]
theta = math.degrees(math.atan(player_rect.x - mousey/ player_rect.y - mousex))
dx = math.cos(theta)
dy = math.sin(theta)
particles.append(Particle(dx, dy, player_rect.x, player_rect.y))
for particle in particles:
particle.draw(screen)
player_rect = pygame.Rect(100, 150, 10, 10)
pygame.draw.rect(screen, RED, player_rect)
clock.tick(FPS)
pygame.display.update()
pygame.quit()