首页 > 解决方案 > 我如何让球开始移动?

问题描述

如何在弹球游戏中开始在屏幕上移动球。当球到达边界时,我试图将球的时间设为 -1,但我认为代码编写不正确。我需要球像普通弹球游戏中的球一样移动。我对碰撞等不太熟悉,但我正在努力学习它。

import pygame

pygame.init()
win = pygame.display.set_mode((1000, 700))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()
balls = []
run = True

class player():
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 10


def redrawGameWindow():
    win.fill((0, 0, 0))
    pygame.draw.rect(win, (255, 0, 0), (player1.x, player1.y, player1.width, player1.height))
    pygame.draw.rect(win, (255, 0, 0), (player2.x, player2.y, player2.width, player2.height))
    pygame.draw.circle(win, ball.colour, (ball.x, ball.y), ball.radius)
    pygame.display.update()


class projectile(object):
    def __init__(self, x, y, radius, colour):
        self.x = x
        self.y = y
        self.radius = radius
        self.colour = colour
        self.vel = 7


ball = projectile(500, 350, 15, (225,225,225))
player1 = player(30, 275, 30, 150)
player2 = player(940, 275, 30, 150)

while run:
    clock.tick(30)
    neg = -1

    keys = pygame.key.get_pressed()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    if keys[pygame.K_w] and player1.y > player1.vel:
        player1.y -= player1.vel
    if keys[pygame.K_s] and player1.y < 700 - player1.height - player1.vel:
        player1.y += player1.vel
    if keys[pygame.K_UP] and player2.y > player2.vel:
        player2.y -= player2.vel
    if keys[pygame.K_DOWN] and player2.y < 700 - player2.height - player2.vel:
        player2.y += player2.vel

    if keys[pygame.K_SPACE]:
        if ball.x > 0 and ball.y > 0:
            ball.y -= ball.vel
            ball.x -= ball.vel
        if ball.y == 1:
            ball.y *= neg

    redrawGameWindow()

pygame.quit()

标签: pygame

解决方案


if ball.y == 1:
    ball.y *= neg

这看起来奇怪,否定了球的位置。更常见的是有一个位置和一个向量(在“大小和方向”的数学意义上,而不是“数组”的编程意义上)指示如何随时间改变位置(a)

例如,一个具有固定y位置的向右 1 的球会是这样的:

xpos = 0, ypos = 20
xincr = 1, yincr = 0
while true:
    xpos += xincr
    ypos += yincr
    drawAt(xpos, ypos)

然后您可以根据条件调整向量(xincryincr值),例如从墙壁上反弹(Python 风格的伪代码):

xpos = radius, ypos = radius, xincr = 1, yincr = 1
while true:
    xpos += xincr, ypos += yincr
    drawAt(xpos, ypos)
    if xpos == radius or xpos == screenWidth - radius - 1:
        xincr *= -1
    if ypos == radius or ypos == screenHeight - radius - 1:
        yincr *= -1

(a)而且,是的,我可以看到你有一个速度变量,但是:

  • 它并没有真正拆分为xy组件,因此不合适;和
  • 它永远不会改变。

推荐阅读