0
votes

I created a sprite which moves in a circular motion. I want to change the direction if the mouse button (touch) is clicked, but when the mouse is clicked, the direction does not change.

This is my code:

  create: function() {
    this.stage.backgroundColor = '#FFFFFF';
    x = this.world.centerX;
    y = this.world.centerY;

    this.direction = 1;
    this.speedDelta = 0.002;
    this.radius = 114;
    this.physics.startSystem(Phaser.Physics.ARCADE);

    //adding player
    this.player = this.add.sprite(x, y, 'player');
    this.player.anchor.setTo(0.5, 0.5);
    this.game.physics.arcade.enable(this.player);

    this.input.onDown.add(this.changeDirection, this);
  },

  update: function() {
    if (this.direction == 1) {
      this.speedDelta = 0.002;
    } else if (this.direction == 1) {
      this.speedDelta = -0.002;
    }
    var period = this.time.now * this.speedDelta;

    this.player.x =  Math.cos(period) * this.radius;
    this.player.y =  d + Math.sin(period) * this.radius;
  },

  changeDirection: function() {
    this.direction = -this.direction;
  }
}
1
You check for direction == 1 twice. - Jongware
thank you for your reply, i changed the second checking to direction == -1 but still it doesn't work. - kemz

1 Answers

0
votes

Your basic assumptions about the behavior of cos and sin are incorrect. You can't simply change the sign of the input and get a different answer.

Notice:

cos(pi/4) = 0.707
cos(-pi/4) = 0.707

sin(pi/4) = -0.707
sin(-pi/4) = -0.707

Also I think your code would benefit by using a slightly different approach in general.

Currently you're recalculating the position from scratch on every update cycle. To get the behavior you want, I think it would be simpler to instead calculate a location delta based off of the speed and direction, then simply add the delta to the current location.

That would also allow you to eliminate your conditional statement, which will make the code cleaner.