在弹球游戏中,如何开始在屏幕上移动球。当到达边界时,我尝试将球的时间减为-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()
答案 0 :(得分:1)
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)
然后,您可以根据条件调整矢量(xincr
和yincr
的值),例如从墙壁弹跳(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)是的,我可以看到您有一个速度变量,但是:
x
和y
组件,因此不合适。和