首页 > 解决方案 > 如何通过点击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()

标签: pythonpygamecoordinatesmovedirection

解决方案


我建议将方向存储在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))

另请参阅运动和运动


完整示例:

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()

推荐阅读