【问题标题】:Pygame - all objects are drawn to the same locationPygame - 所有对象都被绘制到同一个位置
【发布时间】:2021-08-24 20:13:26
【问题描述】:

我有一个类可以在屏幕上绘制对象

我的班级:

class Sword():
    def __init__(self, image, rect, speed, center):
        self.image = image
        self.rect = rect
        self.rect.x,self.rect.y = center #set x and y position
        self.speed = speed
        self.alive = True

    def live(self, enemy): #check if the image touches any object
        if self.rect.colliderect(enemy):
            self.alive = False
            mixer.music.play()

    def update(self): #move object
        self.rect.x += self.speed

    def draw(self, surface): #display object
       if self.alive:
            surface.blit(self.image, (self.rect))

我尝试使用循环添加一些对象:

extend = []#object array
liste = [100,200,300]#object points x and y    
image= pygame.image.load('sword.png')
rect = image.get_rect()

for i in range(3):
    extend.append(Sword(image,rect,1,(liste[i],liste[i])))

while True:
    for tile in extend:
        tile.draw(display)

在我的主循环中,我调用了这个列表,但它根据最后一个位置绘制了所有图像 Exp:rect<300,300,120,40>

为什么它会将所有对象绘制在同一个位置?

【问题讨论】:

  • 什么是sword.get_rect()
  • 得到图片的rect exp: rect
  • 但是sword是什么?
  • 我正在使用 pygame 模块制作游戏,Sword 类在屏幕上绘制了一些东西
  • 是的,我看到Sword 是一个类。 sword 是什么?

标签: python class pygame


【解决方案1】:

看起来rect 是一个单独的对象,所以当您更新它时,最后一个坐标获胜。您需要制作一份副本:

from copy import copy

rect = image.get_rect()

for i in range(3):
    extend.append(Sword(image,copy(rect),1,(liste[i],liste[i])))

在您的Sword 类中,您不断更新同一实例的xy 属性:

        self.rect = rect
        self.rect.x,self.rect.y = center #set x and y position

rect 是同一个实例:来自image.get_rect() 的实例。

【讨论】:

  • 您的解决方案有效,但我仍然不明白哪里出错了我从未更新过 rect 变量
  • @Django 你做了self.rect.x,self.rect.y = center,改变了rect 也引用的矩形对象。
  • @khelwood 感谢您的解释,所以我整晚都发疯了,我的代码 c++ 在哪里:=)
猜你喜欢
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多