sand
sand

Reputation: 183

Move a sprite along a particular direction cocos2d

I want to move a sprite along a particular direction until next keypress in 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?

Upvotes: 0

Views: 900

Answers (1)

user2373682
user2373682

Reputation:

How do you call the function 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. 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.

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

If you want to use actions, Move action is good for this.

Upvotes: 1

Related Questions