我第一次玩pygame,尝试让多个矩形在屏幕上移动。这是我的代码:
import pygame
pygame.init()
scrWidth = 1200
scrHeigth = 900
done = False
rectangles = []
screen = pygame.display.set_mode((scrWidth, scrHeigth))
clock = pygame.time.Clock()
class Rectangle:
speed = [1,1]
colourSpeed = 300
colourID = 0
colour = (0, 0, 255)
size = 60
def __init__(self, name = "", x=0, y=0, speed=False, colour=False, size=False):
self.name = name
self.x = x
self.y = y
self.doesSpeed = speed
self.doesColour = colour
self.doesSize = size
def draw(self):
pygame.draw.rect(screen, self.colour, pygame.Rect(self.x, self.y, self.size, self.size))
def checkCollision(self):
if self.x < 0 or self.x > scrWidth-self.size:
self.speed[0] = -self.speed[0]
if self.y < 0 or self.y > scrHeigth-self.size:
self.speed[1] = -self.speed[1]
def move(self):
self.x += self.speed[0]
self.y += self.speed[1]
def changeColour(self):
self.colourID = (self.colourID+1)%self.colourSpeed
if 0 <= self.colourID < (self.colourSpeed/3):
self.colour = (0, 0, 255)
elif (self.colourSpeed/3) <= self.colourID < (2*self.colourSpeed/3):
self.colour = (0, 255, 0)
elif (2*self.colourSpeed/3) <= self.colourID < self.colourSpeed:
self.colour = (255, 0, 0)
rect1 = Rectangle("rect1", 30, 30, False, True, False)
rectangles.append(rect1)
rect2 = Rectangle("rect2", 300, 300)
rectangles.append(rect2)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
screen.fill((0, 0, 0))
for obj in rectangles:
obj.checkCollision()
if obj.doesColour: obj.changeColour()
obj.move()
obj.draw()
pygame.display.flip()
clock.tick(60)
问题是当矩形与屏幕边缘碰撞时,所有矩形都会改变方向(速度)。但是,如果我制作不同速度的矩形,则不会发生这种情况。
ex:rect1的速度为[1,1],rect2的速度为[2,2]。
造成这种情况的原因是什么?如何解决?
答案 0 :(得分:1)
将speed,colourSpeed,colourID,颜色,大小移动到 init 方法。
此时,字段被定义为类字段,因此它们将针对所有矩形进行全局更改。
<强>解决方案强>:
def __init__(self, name = "", x=0, y=0, speed=False, colour=False, size=False):
self.name = name
self.x = x
self.y = y
self.doesSpeed = speed
self.doesColour = colour
self.doesSize = size
# here it comes
self.speed = [1,1]
self.colourSpeed = 300
self.colourID = 0
self.colour = (0, 0, 255)
self.size = 60