如何在精灵类内部的屏幕上绘制对象?
因此,我试图使用精灵在顶部用另一个矩形绘制一个矩形。我为玩家做了一堂课,并做了一些基本的设置,但是当我试图在顶部打开第二个矩形时,它无效。我进行了一些测试,发现我什至无法从该播放器课内绘制线条或矩形。
这是我的基本测试代码:
import pygame as pg
pg.init()
width, height = 800, 800
screen = pg.display.set_mode((width, height))
run = True
class Player(pg.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pg.image.load("test_image.png")
self.rect = self.image.get_rect()
def update(self):
pg.draw.rect(screen, [0, 255, 0], (200, 200, 100, 50))
print("test")
def draw_window():
screen.fill((255, 255, 255))
playerGroup.draw(screen)
pg.display.update()
playerGroup = pg.sprite.GroupSingle()
playerGroup.add(Player())
while run:
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
playerGroup.update()
draw_window()
这是我得到的: image
蓝色的东西是玩家图像通常在左上角被绘制。然而,我要在更新方法中绘制的矩形无处可见,即使我可以清楚地看到该方法被打印(“测试”)。对于pg.draw()而言,这不仅是正确的
。
So I'm trying to draw a rectangle with another rectangle on top, using Sprites. I made a class for the player and did some basic setup, but when I tried to blit the second rectangle on top, it didn't work. I did some testing and found out that I can't even draw lines or rectangles from inside this player class.
Here's my basic testing code:
import pygame as pg
pg.init()
width, height = 800, 800
screen = pg.display.set_mode((width, height))
run = True
class Player(pg.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pg.image.load("test_image.png")
self.rect = self.image.get_rect()
def update(self):
pg.draw.rect(screen, [0, 255, 0], (200, 200, 100, 50))
print("test")
def draw_window():
screen.fill((255, 255, 255))
playerGroup.draw(screen)
pg.display.update()
playerGroup = pg.sprite.GroupSingle()
playerGroup.add(Player())
while run:
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
playerGroup.update()
draw_window()
This is what i get: image
The blue thing is the player image that gets drawn normally in the top left corner. The rect that i'm trying to draw inside the update() method however is nowhere to be seen, even though i can clearly see the method gets called with the print("test"). This isn't just true for pg.draw() but also for surface.blit()
Why is this and how do i fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
screen.fill((255, 255, 255))
用白色填充整个显示屏。之前绘制的任何内容都将丢失。您必须在清除显示之后和更新显示之前调用playerGroup.update()
。例如:screen.fill((255, 255, 255))
fills the entire display with a white color. Anything previously drawn will be lost. You must callplayerGroup.update()
after clearing the display and before updating the display. e.g.: