Jump to content

Mouse control for sprite?


ekeimaja
 Share

Recommended Posts

I am learning Phaser as creating sidescroller, where controlling of direction is with mouse.

 

I have made movement like this:

         if(this.player.x < this.game.input.activePointer.x){                         this.player.scale.x = 1;            this.player.animations.play('right');            this.player.body.velocity.x = 250;        }        else if(this.player.x > this.game.input.activePointer.x){                    this.player.scale.x = -1;            this.player.animations.play('left');            this.player.body.velocity.x = -250;               }             else{            this.player.animations.stop();            this.player.body.velocity.x = 0;        }

Sprite moves first normally to right, but then it starts to flicker between frames, because mouse endpoint is in that location.

 

post-14652-0-05537300-1443024126.jpg

 

It makes this also if mouse is keeped in middle. Is there any way to get this work, or do I have to do movement on keyboard?

Link to comment
Share on other sites

You can also use Phaser.Math.fuzzyEqual as the first set of if checks.

To expand on this, the problem is your character is bouncing back and forth between being on the left of the pointer and the right of the pointer.  It's the classic movement problem, you need to have a properly defined "stop" state, otherwise the velocity on the sprite will push it to the other side of the pointer, causing it to turn around and jump to the other side, repeating every frame and giving you this behavior.

You should use Phaser.Math.fuzzyGreaterThan and Phaser.Math.fuzzyLessThan to add some "padding" to the end point, to allow your sprite to reach it, and overshoot it, while still stopping.

        var marginOfError = 5; //increase this until the behavior stops.             if(Phaser.Math.fuzzyLessThan(this.player.x, this.game.input.activePointer.x, marginOfError)){                         this.player.scale.x = 1;            this.player.animations.play('right');            this.player.body.velocity.x = 250;        }         else if(Phaser.Math.fuzzyGreaterThan(this.player.x, this.game.input.activePointer.x, marginOfError)){                    this.player.scale.x = -1;            this.player.animations.play('left');            this.player.body.velocity.x = -250;               }             else{            this.player.animations.stop();            this.player.body.velocity.x = 0;        }

It's hard to associate velocity and position, because a velocity of 250 doesn't mean the sprite will move 250px in a single update cycle.  you'll have to increase the margin of error until the behavior stops.  Using the width of the sprite for this value might work.

Good luck!

 

~Cudabear

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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