简体   繁体   English

沿着特定方向移动精灵cocos2d

[英]Move a sprite along a particular direction cocos2d

I want to move a sprite along a particular direction until next keypress in cocos2d. 我想沿着特定方向移动精灵,直到在cocos2d中下一次按键。

The code to handle a keypress is as follows, 处理按键的代码如下,

    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")
        ...

I tried this function which calls the above function to keep the sprite moving along a direction, 我尝试了此函数,该函数调用上面的函数以保持精灵沿一个方向移动,

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

but the sprite easily goes beyond the screen boundaries, Is there a way to make the sprite move along the direction in a controlled fashion? 但精灵容易超越屏幕边界,是否有办法使精灵以受控方式沿方向移动?

How do you call the function keep_going ? 您如何调用函数keep_going If it's in a simple loop, then it gets called too often and the sprite probably moves so fast that it disappears instantly. 如果它处于一个简单的循环中,则它会被调用得太多,并且精灵可能移动得如此之快,以至于立即消失。

I assume here that self in your code is some layer. 我在这里假设代码中的self是某一层。 You can change the signature of the function to def keep_going(self, dt, DIRECTION) and then, for example in the layer's constructor, call self.schedule_interval(self.keep_going, 0.1, 'left') to update the sprite's position 10 times in a second. 您可以将函数的签名更改为def keep_going(self, dt, DIRECTION) ,然后例如在图层的构造函数中,调用self.schedule_interval(self.keep_going, 0.1, 'left')以将精灵的位置更新10次一秒钟。

Another possibility is to use the schedule function which schedules a function to be run constantly, not in fixed intervals. 另一种可能性是使用调度功能,该功能调度要恒定而不是固定间隔运行的功能。 In that case you have to modify your function more. 在这种情况下,您必须更多地修改功能。 I suggest setting a velocity to the sprite based on input, and then computing the new position in pixels. 我建议根据输入为子画面设置速度,然后以像素为单位计算新位置。 There's a good example in the cocos package in samples/balldrive_toy_game/balldrive_toy_game.py 在cocos包中的sample / balldrive_toy_game / balldrive_toy_game.py中有一个很好的例子。

If you want to use actions, Move action is good for this. 如果要使用动作,则“ 移动动作”非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM