roosterchair Posted January 31, 2016 Share Posted January 31, 2016 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 More sharing options...
Batzi Posted January 31, 2016 Share Posted January 31, 2016 I made this quickly but let me know if that's what you want: http://phaser.io/sandbox/edit/wZYaHbZA Go to Play and move using the cursors (left,right,up,down) and press E to change sprites. Link to comment Share on other sites More sharing options...
roosterchair Posted January 31, 2016 Author Share Posted January 31, 2016 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! Batzi 1 Link to comment Share on other sites More sharing options...
roosterchair Posted January 31, 2016 Author Share Posted January 31, 2016 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. Batzi 1 Link to comment Share on other sites More sharing options...
Batzi Posted January 31, 2016 Share Posted January 31, 2016 You're welcome! Link to comment Share on other sites More sharing options...
Recommended Posts