如何通过点击 pygame 中的按键来改变球的方向?

How to change my ball direction by clicking keys in pygame?

我有问题。我的球一直在 8 个方向中的 1 个方向移动,但是当我单击向左或向右箭头时,我想改变方向并以平滑的弧线转动。我需要建议我应该为键的条件写什么。我是初学者,但这是我的代码:

import pygame
pygame.init()
import random

win = pygame.display.set_mode((1280,720))

x = random.randint(150,1130)
y = random.randint(150,570)
vel = 1
x_direction = random.randint(-vel, vel)
y_direction = random.randint(-vel, vel)

while True:
    x += x_direction
    y += y_direction
    
    pygame.time.delay(10)
    
    keys = pygame.key.get_pressed()
            
    if keys[pygame.K_LEFT]:
        pass
    
    if keys[pygame.K_RIGHT]:
        pass
    
    win.fill((0,0,0))
    pygame.draw.circle(win, (255,0,0), (x, y), 6)
    pygame.display.update()

pygame.quit()

我建议将方向存储在 pygame.math.Vector2 对象中:

direction = pygame.math.Vector2(x_direction, y_direction)

通过 rotate_ip():

旋转向量来改变方向
if keys[pygame.K_LEFT]:
    direction.rotate_ip(-1)

if keys[pygame.K_RIGHT]:
    direction.rotate_ip(1)

x += direction.x
y += direction.y

你不能使用 rotate 创建一个随机方向的矢量:

direction = pygame.math.Vector2(1, 0).rotate(random.randint(0, 360))

另见 Motion and movement


完整示例:

import pygame
import random
pygame.init()
win = pygame.display.set_mode((1280,720))
background = pygame.Surface(win.get_size(), pygame.SRCALPHA)
background.fill((0, 0, 0, 1))
clock = pygame.time.Clock()

x = random.randint(150,1130)
y = random.randint(150,570)
direction = pygame.math.Vector2(1, 0).rotate(random.randint(0, 360))

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        direction.rotate_ip(-1)
    if keys[pygame.K_RIGHT]:
        direction.rotate_ip(1)

    x = max(0, min(direction.x + x, win.get_width()))
    y = max(0, min(direction.y + y, win.get_height()))
    
    win.blit(background, (0, 0))
    pygame.draw.circle(win, (255,0,0), (round(x), round(y)), 6)
    pygame.display.update()

pygame.quit()