Jump to content

control two sprites with arrows on different turns


roosterchair
 Share

Recommended Posts

I have multiple sprites that I'd like to each control with the arrows in a turn-based way. i.e. move sprite1 around screen with arrows then press 'E' to switch to controlling sprite2 with  arrow keys. Repeat back and forth. I've tried many methods, looked through many examples, read Interphase 1, and googled for hours. I can't seem to figure this one out.

Here's the relevant code:

currentPlayer = "Guy"; //this.player1

if (currentPlayer == "Guy") {
    movingPlayer = this.player1;
} else {
  movingPlayer = this.player2;
}

//the conditional doesn't work, but if I set it outside the conditional it's fine
//movingPlayer = player1 works fine.

this.cursors.right.onDown.add(this.moveRight, this, 0, movingPlayer);

moveRight: function (key, player) {
                    
        player.x += TILE_SIZE;
        
}

So if I set movingPlayer manually before I run the game it works fine. It passes the correct player to the moveRight function and everything is great. However, I CAN NOT for the life of me set movingPlayer dynamically. I've tried it in the update function, in the create function, in its own function, and nothing works.

Is there a good tutorial, example, code snippet, or advice on how to have two sprites on the screen that can both be controlled by the arrow keys on different turns?

Thanks!

Link to comment
Share on other sites

This looks really great! Thank you so much. I think my problem is that I need to move the sprite once per onDown event. I apologize, I should have been more explicit about this. 

Can you think of a way to move these sprites in a set amount of pixels once for every key press? Your example is excellent... I just need to prevent the sprite from continuously moving while the arrow keys are pressed.

Thanks again!

Link to comment
Share on other sites

Hey, looks like your example works great if I manually add a key and function for each arrow instead of creating cursors and checking in the update.

Something like this:

keyDown = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
keyDown.onDown.add(moveSprite, this);

function moveSprite() {
        character.y += 75;
}

Thanks again for your help! I tried it in my own code and it works perfectly.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...