pygame-数学向量。报告声明的参数和实际参数之间的差异

时间:2019-02-16 02:11:43

标签: python pygame

大家好,我是python的新手,所以我开始关注YouTubers来创建游戏。我在下面附加了我的代码,并从PyGame导入了Vector2。但问题出在第16行 self.pos = Vector2(width/2,height/2)之后。皮查姆(Pycharm)提醒我,论据是错误的。

运行程序时出现此错误。

self.pos += self.vel + ( 0.5*self.acc.x ) #d = v +0.5` a formula to calculate dist
     

AttributeError:“元组”对象没有属性“ x”。

请帮助谢谢。

将pygame导入为pg 从设置导入* 从pygame.math导入Vector2

class Player(pg.sprite.Sprite):

def __init__(self):
    pg.sprite.Sprite.__init__(self)
    self.image = pg.Surface((30,40)) #simple sprite
    self.image.fill(yellow) #color of sprite
    self.rect = self.image.get_rect()
    self.rect.center = (width/2,height/2) #centre the sprite
    self.pos = Vector2(width/2, height/2)  #position vector
    self.vel = Vector2(0,0) #velocity vector
    self.acc = Vector2 (0, 0)  #accelaration vector

def update(self):
    self.acc = (0,0)
    keys = pg.key.get_pressed() #if pressed
    if keys[pg.K_LEFT]:
        self.acc.x = -0.5  #accelarate left
    if keys[pg.K_RIGHT]:
        self.acc.x = 0.5  #accelarate right

    self.vel += self.acc #velocity adds to acceleration
    self.pos += self.vel + ( 0.5*self.acc.x ) #d = v +0.5a  formula to calculate dist

    self.rect.center = self.pos  

1 个答案:

答案 0 :(得分:0)

在构造函数中,属性self.accpygame.math.Vector2初始化。此时self.acc.x是有效的,因为Vector2的对象具有属性x

 def __init__(self):

     # [...]

     self.acc = Vector2 (0, 0)  #accelaration vector

但是在方法update中,元组被分配给属性self.acc

def update(self):
    self.acc = (0,0)

这会导致错误

  

AttributeError:“元组”对象没有属性“ x”。

当您尝试访问self.acc.x时,由于元组没有属性x,因此:

将行self.acc = (0,0)替换为self.acc = Vector2(0, 0),以解决此问题:

def update(self):

    self.acc = Vector2(0, 0)

    keys = pg.key.get_pressed() #if pressed
    if keys[pg.K_LEFT]:
        self.acc.x = -0.5  #accelarate left
    if keys[pg.K_RIGHT]:
        self.acc.x = 0.5  #accelarate right

    self.vel += self.acc #velocity adds to acceleration
    self.pos += self.vel + ( 0.5*self.acc.x ) #d = v +0.5a  formula to calculate dist

    self.rect.center = self.pos
相关问题