python - 如何通过点击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))
另请参阅运动和运动。
完整示例:
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()
推荐阅读
- arrays - 这个函数的返回值是什么
- python - 无法使用 selenium 从页面中名为“heading”的每个类中获取数据
- asp.net-mvc - 首先生成下拉asp.net mvc代码
- javascript - JS 字符串字面量
- javascript - 为什么空数组通过 if(array !== []) 检查
- sql - mariadb json中正确使用json_table
- python - 使用 python-crontab 的多个作业
- python - Flask URL 像这样“/api/hello”工作,但不像这样“/api/hello/”
- regex - 匹配浮点数或整数的正则表达式,可以是正数或负数
- html - 使用 get 方法将表单绑定到 GetMapping 控制器时出现问题