打电话给ball.update()
时,我希望球应该移动,但没有移动。
[我正在考虑将bpos
定义为矩形对象并将其传递到椭圆形以将球吸引到屏幕上可能存在问题。
bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
我使bpos成为rect对象,然后将其传递以绘制椭圆的原因:
class Ball:
def __init__(self):
self.x = screen_width // 2
self.y = screen_height // 2
self.speed = 5
self.vx = self.speed
self.vy = self.speed
def draw(self, screen):
pygame.draw.ellipse(screen, light_grey, bpos)
def update(self):
self.x += self.vx
self.y += self.vy
是因为最终,当要使球保持界限时,如果可能的话,我想在这种更新方法中使用pygame Rect属性(上,下,左,右)。
def update(self):
self.x += self.vx
self.y += self.vy
**if self.top <= 0 or self.bottom >= screen_height:
self.vy *= -1
if ball.left <= 0 or self.right >= screen_width:
self.vx *= -1**
But the ball isnt moving.
在游戏逻辑中,您可以看到我在打电话:
ball.draw(屏幕)ball.update()
非常感谢您的投入。谢谢。下面是我的代码。
import pygame, sys
class Paddle:
def __init__(self):
self.rect = pygame.Rect(10, screen_height / 2 - 70, 10, 140)
def draw(self, screen):
pygame.draw.rect(screen, light_grey, self.rect)
class Ball:
def __init__(self):
self.x = screen_width // 2
self.y = screen_height // 2
self.speed = 5
self.vx = self.speed
self.vy = self.speed
def draw(self, screen):
pygame.draw.ellipse(screen, light_grey, bpos)
def update(self):
self.x += self.vx
self.y += self.vy
# General setup
pygame.init()
clock = pygame.time.Clock()
# Main Window
screen_width = 1280
screen_height = 960
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Pong')
# Colors
light_grey = (200, 200, 200)
bg_color = pygame.Color('grey12')
# Game Rectangles
ball = Ball()
bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
left_paddle = Paddle()
right_paddle = Paddle()
right_paddle.rect.x = screen_width - right_paddle.rect.width
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Game logic
screen.fill(bg_color)
ball.draw(screen)
left_paddle.draw(screen)
right_paddle.draw(screen)
ball.update()
pygame.display.flip()
clock.tick(60)
问题不是您在bpos
中使用了rect。 @Matthias在评论中已经提到的问题是您不更新bpos
。
需要在您的Ball.update()
中进行更新。
注意,您使用的矩形应该是Ball实例的属性。您应该在init中对其进行初始化,并使用self.rect.x和self.rect.y来更新和跟踪球的位置。不要同时在self.rect.x和self.rect.y中以及单独在self.x,self.y中保持位置。这只会导致冗余,并可能导致不一致和错误。