2014-01-09 33 views
0

我要定义一个函数来设定速度,以人物在我比赛的节奏,我知道有这个公式:设置字符

rate * time = distance 

1. Establish a rate of movement in whatever units of measure you want (such as pixels per millisecond). 
2. Get the time since the last update that has passed (elapsed time). 
3. Establish the direction of movement . 

我已经tryied定义它实现方法这个:

def speed(self, speed): 
    clock = pygame.time.Clock()  
    milliseconds = clock.tick(60) # milliseconds passed since last frame 
    seconds = milliseconds/1000.0 
    speed = seconds * (self.dx+self.dy) 

但是当我调用这个方法来改变我角色的速度时,没有任何反应。

有什么建议吗?

+0

你对速度做了什么?你在哪里调用这个函数? –

+0

你似乎忘了添加'return speed'。 –

+0

这是为了*设定*速度还是要*取得它?为什么它有一个“速度”参数? – jonrsharpe

回答

1

您需要使用self关键字,以便在方法中设置类属性。但在你的方法中,你使用速度作为参数,我不相信你是如何使用它的。

def speed(self, speed): 
    clock = pygame.time.Clock()  
    milliseconds = clock.tick(60) # milliseconds passed since last frame 
    seconds = milliseconds/1000.0 
    speed = seconds * (self.dx+self.dy) 

该方法需要一定的速度,然后将其设置为等于某个值,然后超出范围而无需进行更改。与你将一个方法来设置对象speed属性:

def set_speed(self): 
    clock = pygame.time.Clock()  
    milliseconds = clock.tick(60) # milliseconds passed since last frame 
    seconds = milliseconds/1000.0 
    self.speed = seconds * (self.dx+self.dy) 

self是从里面它的一个方法引用的对象的方式。方法之外的self.speed = 10等同于做my_object.speed = 10。使用这种方法:

class Character: 
    def __init__(): 
     self.speed = 0 # your character class needs to have a speed attribute somewhere 

hero = Character() # creates an object that represents your character 
hero.set_speed() # call the method to set the speed attribute of the character class 
+0

这不改变字符的速度 –

+0

更新了代码。我第一次误读了OP。 – IanAuld

+0

如果你不能在内部传递速度,你为什么要调用hero.set_speed()? –

0

我不知道究竟如何你拥有了一切成立,但在这里是用2元组(x, y)positionspeed(我想你可能有self.x, self.yself.position和粗糙例如self.dx, self.dyself.speed,但原理是一样的):

def Character(object): 

    def __init__(self, position): 
     self.position = position # e.g. (200, 100) 
     self.speed = (0, 0) # start stationary 

    def move(self, elapsed): 
     """Update Character position based on speed and elapsed time.""" 
     #       distance = time * rate 
     # position =  old position + distance 
     self.position = (int(self.position[0] + (elapsed * self.speed[0])), 
         int(self.position[1] + (elapsed * self.speed[1]))) 

请注意,您并不需要制定出多远Character宜游对于给定速度,当你设置self.speed,正当您尝试moveCharacter。您可以直接访问character.speed;具有“setter”方法(例如set_speed(self, speed))是不扩张的。现在

你可以称之为:

hero = Character(start_loc) 
framerate = 60 
clock = pygame.time.Clock() 
... 
while True: # main gameplay loop 
    elapsed = clock.tick(60) # update world time and get elapsed 
    ... 
    hero.speed = (2, 0) # travelling horizontally in the positive x-direction 
    hero.move(elapsed) # update the hero's position 

请注意,这里的速度将是每毫秒像素为单位。