【问题标题】:Move a sprite along a particular direction cocos2d沿特定方向移动精灵 cocos2d
【发布时间】:2015-05-24 03:48:42
【问题描述】:

我想沿特定方向移动精灵,直到 cocos2d 中的下一次按键。

处理按键的代码如下,

    def on_key_press(self, symbol, modifiers):
    if symbol == key.LEFT:
        DIRECTION="left"
        before=self.player.position
        height=self.player.position[1]
        width=self.player.position[0]-1
        self.player.position=width,height
        self.player.rotation=-90
        if(height>=600 or height<=0):
            print ("you lose)
        if(width>=800 or width<=0):
            print ("you lose)


    elif symbol == key.RIGHT:
        DIRECTION="right"
        before=self.player.position
        height=self.player.position[1]
        width=self.player.position[0]+1
        self.player.position=width,height
        self.player.rotation=90
        if(height>=600 or height<=0):
            print ("you lose)
        if(width>=800 or width<=0):
            print ("you lose")
        ...

我试过这个函数,它调用上面的函数来保持精灵沿着一个方向移动,

    def keep_going(self,DIRECTION):
        if(DIRECTION=="left"):
            self.on_key_press(key.LEFT,512)
        ...

但是精灵很容易超出屏幕边界,有没有办法让精灵以可控的方式沿着方向移动?

【问题讨论】:

    标签: python cocos2d-x cocos2d-python


    【解决方案1】:

    如何调用函数keep_going?如果它在一个简单的循环中,那么它会被过于频繁地调用,并且精灵可能移动得太快以至于它会立即消失。

    我在这里假设您的代码中的self 是某个层。您可以将函数的签名更改为def keep_going(self, dt, DIRECTION),然后,例如在图层的构造函数中,调用self.schedule_interval(self.keep_going, 0.1, 'left') 以在一秒钟内更新精灵的位置10 次。

    另一种可能性是使用schedule 函数,该函数将函数调度为不断运行,而不是以固定的时间间隔运行。在这种情况下,您必须更多地修改您的功能。我建议根据输入设置精灵的速度,然后以像素为单位计算新位置。在 samples/balldrive_toy_game/balldrive_toy_game.py 的 cocos 包中有一个很好的例子

    如果你想使用动作,Move 动作很适合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多